个人学习笔记 - 扩展运算符和Array.from的使用差异

193 阅读1分钟

用扩展运算符对数组浅拷贝

const aTest = [1, 2, 3];
const aTest2 = [...aTest, 4];
console.log(aTest2);

// [1, 2, 3, 4]

...运算符而不是Array.from将一个可迭代对象 转换成数组

//普通对象不可迭代,需要内置Symbol.iterator迭代器
const oTest = {  
    data: [1, 2, 3],
    [Symbol.iterator]() {
        let index = 0;
        return {
            next: () => {
                if (index < this.data.length) {
                    return {value: this.data[index++], done:false}
                } else {
                    return {done: true}
                }
            }
        }
    }
};
const aTest = [...oTest]
console.log(aTest);

//Array.from也无法将非类数组对象遍历为数组
const aTest2 = Array.from(oTest1)
console.log(aTest2);

//Array.from可以将类数组对象转化为数组
const oTest3 = {0:1, 1:2, 2:3, length:3};
const aTest3 = Array.from(oTest3);
console.log(aTest3);

//[1, 2, 3]
//[]
//[1, 2, 3]

Array.from而不是...运算符去做map遍历可避免创建新数组

const aTest = [1, 2, 3];
const aTest1 = item => item + 1;

//bad
const aTest2 = [...aTest].map(aTest1);

//good
const aTest3 = Array.from(aTest, aTest1);

console.log('aTest2',aTest2);
console.log('aTest3',aTest3);
//[2, 3, 4]
//[2, 3, 4]