【问题标题】:How to assign new value array to old array inside method?如何将新值数组分配给方法内的旧数组?
【发布时间】:2020-09-12 19:03:01
【问题描述】:

我的方法很多,标准filtermap等返回一个新数组。

let array = [1, 2, 3, 4];
array = someFilter(array);
array = otherFilter(array);
array = someMap(array);

不返回新数组怎么办?

let array = [1, 2, 3, 4];
someFilter(array);
otherFilter(array);
someMap(array);

例如

let x = [1, 2, 3, 4];
filter(x);
// x still 1, 2, 3, 4

function filter(array){
    let newArray = array.filter((item) => item % 2 == 0);
    array = newArray; // what do here?
}

更新

有我的解决方案

function replace(oldArray, newArray){
    oldArray.length = 0;
    push(oldArray, newArray);
}

function push(sourceArray, ...additionalArray) {
    additionalArray.forEach((array) => {
        if (array.length < 1000){
            sourceArray.push.apply(sourceArray, array);
        } else {
            array.forEach((item) => sourceArray.push(item));
        }
    });
    return sourceArray;
}

【问题讨论】:

    标签: javascript arrays filter slice


    【解决方案1】:

    使用Array.splice()从原始数组中删除所有项,并从新数组中添加项:

    function filter(array) {
      const newArray = array.filter((item) => item % 2 == 0);
      array.splice(0, array.length, ...newArray);
    }
    
    const x = [1, 2, 3, 4];
    
    filter(x);
    
    console.log(x)

    您还设置数组的长度为 0 以删除所有项目,然后推送新项目:

    function filter(array) {
      const newArray = array.filter((item) => item % 2 == 0);
      array.length = 0;
      array.push(...newArray);
    }
    
    const x = [1, 2, 3, 4];
    
    filter(x);
    
    console.log(x)

    【讨论】:

    • 它可以处理困难的项目吗?例如,[ { key: { name: { first: 'first', last: 'last' } } }, ... ]
    • 这种方式会改变原始数组,非原始项目不会被克隆 - 对项目的引用从一个数组复制到另一个数组。
    • 是的,够了the reference to the item is moved from one array to another。我很困惑元素被删除了。
    • 如果array有很多项目(1000、5000),那么...newArray操作是否有问题?
    • 扩展运算符不是堆栈安全的,这意味着如果项目太多,它可能会导致堆栈溢出。我已经使用了大约 70-80Ks 的散布,没有问题。如果您要处理这种大小的数组,我建议使用第二种解决方案,避免传播,并使用简单的循环推送项目。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2020-06-21
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多