JS的一些小技巧

1. 运用Set对象对数组中的值去重

这个技巧的适用范围是数组中的数值的类型为:undefined, null, boolean, string, number。
当包涵object, function, array时,则不适用。

const array = [1, 2, 3, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 5]

2. 截取数组

如果您想从数组的末尾删除值,有比使用splice()更快的替代方法。
例如,如果你知道原始数组的长度,就可以通过重新定义它的length属性来实现截取。

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

这是一个特别简洁的解决方案。
但是,slice()方法的运行时更快。
如果速度是你的主要目标,考虑使用下面的方式。

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);

console.log(array); // Result: [0, 1, 2, 3]

3. 获取数组中的最后的元素

数组方法slice()可以接受负整数,如果提供它,它将从数组的末尾开始截取数值,而不是开头。

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

4. 对源数据深度克隆

let cloneData = JSON.parse(JSON.stringify(treeData)) // 对源数据深度克隆

5. 把线性数据转成树形数据

function setTreeData(source){
    let cloneData = JSON.parse(JSON.stringify(source))      // 对源数据深度克隆
    return  cloneData.filter(father=>{                      // 循环所有项,并添加children属性
        let branchArr = cloneData.filter(child=> father.id == child.parentId);   // 返回每一项的子级数组
        branchArr.length>0 ? father.children=branchArr : ''   //给父级添加一个children属性,并赋值
        return father.parentId==0;      //返回第一层
    });
}

猜你喜欢

转载自blog.csdn.net/huhao820/article/details/89475871