首页 > 解决方案 > 为什么更改后对连接数组的操作会影响两个数组?

问题描述

我运行以下过程以从对象中收集所有产品属性和选项,以更新产品。

出于某种奇怪的原因,主数组 categoryUrls 发生了变化,我似乎无法理解为什么。

在以下过程之后,categoryUrls[random key].attributes.options获取添加的新值。

const {categoryUrls} = require('./helpers/categoryUrls.js')

getCategory = function (categoryUrls) {

    let att = []
    
    for (const key in categoryUrls) {
        if (categoryUrls[key].attributes) {// check if has attribute 
            att = att.concat(categoryUrls[key].attributes)
            
            for(var i=0; i<att.length; ++i) {// check if attribute ID already exist and remove duplicates
                for(var j=i+1; j<att.length; ++j) {
                    if(att[i].id === att[j].id){
                        for (let k = 0; k < att[j].options.length; k++) { // if attribute ID already exist unite options
                            let exist = att[i].options.find(option => option == att[j].options[k]) // check if option no already exist 
                            if (!exist) {
                                att[i].options.push(att[j].options[k])
                            }
                        }
                        att.splice(j--, 1);
                    }
                }
            }
        }
    }
    return att
}


let data = getCategory(categoryUrls)
productData = productData.concat(data)

标签: javascriptnode.jsarraysconcatenation

解决方案


如果我理解您正在尝试将新数组保存到att中,但让原始数组保持不变,但您正在将过程应用到 categoryUrls。那是对的吗?如果是这样,请记住数组是引用类型,因此,如果您使用它们,您会更改实际的数组,它们不会作为字符串或整数工作。

尝试在工作之前复制阵列并将该过程应用于其副本。

尝试这个:

const {categoryUrls} = require('./helpers/categoryUrls.js')

getCategory = function (categoryUrls) {

    let newArray = [...categoryUrls]

    let att = []
    
    for (const key in categoryUrls) {
        if (categoryUrls[key].attributes) {// check if has attribute 
            att = att.concat(newArray[key].attributes)
            
            for(var i=0; i<att.length; ++i) {// check if attribute ID already exist and remove duplicates
                for(var j=i+1; j<att.length; ++j) {
                    if(att[i].id === att[j].id){
                        for (let k = 0; k < att[j].options.length; k++) { // if attribute ID already exist unite options
                            let exist = att[i].options.find(option => option == att[j].options[k]) // check if option no already exist 
                            if (!exist) {
                                att[i].options.push(att[j].options[k])
                            }
                        }
                        att.splice(j--, 1);
                    }
                }
            }
        }
    }
    return att
}


let data = getCategory(categoryUrls)
productData = productData.concat(data)

推荐阅读