JS 一些注意事项

1对象引用,对象赋值

此图中遍历导致被遍历的值发生改变

JS 一些注意事项

后来这么改了,原来被遍历的list便不会被影响:

let newCategoryTabs = [];

for (var i = 0; i < categoryTabsDefault.length; i++) {
    let newPlProds = [];
    let item = categoryTabsDefault[i];
    console.log("item---i--->" + i + "-->" + JSON.stringify(item));
    for (var j = 0; j < item.plProds.length; j++) {
        let item2 = item.plProds[j];
        console.log("item--->" + JSON.stringify(item2));
        let isThisRecord = false;
        if ((item2.plProduct.CPQ_Product__r.Internal_Model__c.indexOf(searchListItem) != -1) && (item2.plProduct.CPQ_Product__r.Internal_Model__c != undefined) && isThisRecord == false) {
            newPlProds.push(item2);
            isThisRecord = true;
        } else if (isThisRecord == false && (item2.plProduct.CPQ_Product__r.External_Model__c != undefined) && (item2.plProduct.CPQ_Product__r.External_Model__c.indexOf(searchListItem) != -1)) {
            newPlProds.push(item2);
            isThisRecord = true;
        } else if (isThisRecord == false && (item2.plProduct.CPQ_Product__r.Part_No__c != undefined) && (item2.plProduct.CPQ_Product__r.Part_No__c.indexOf(searchListItem) != -1)) {
            newPlProds.push(item2);
            isThisRecord = true;
        } else if (isThisRecord == false && (item2.plProduct.CPQ_Product__r.Product_Name__c != undefined) && (item2.plProduct.CPQ_Product__r.Product_Name__c.indexOf(searchListItem) != -1)) {
            newPlProds.push(item2);
            isThisRecord = true;
        }
    }
    //item.plProds = newPlProds;
    //因为对象的简单和深度克隆(赋值与引用的区别),如果向上面一样直接=会改变categoryTabsDefault的值,所以新建一个对象防止引用赋值导致遍历的list的值发生改变
    let newItem=new Object();
    newItem.id=item.id;
    newItem.name=item.name;
    newItem.plProds=newPlProds;
    console.log("newItem---》"+JSON.stringify(newItem));
    newCategoryTabs.push(newItem);
}
console.log("newCategoryTabs--333->" + JSON.stringify(newCategoryTabs));
console.log("categoryTabsDefault--22222->" + JSON.stringify(categoryTabsDefault));

 

具体需要去了解一下JS对象简单、深度克隆(赋值与引用的区别)

参考:https://blog.csdn.net/pugongyingyangyue/article/details/74928646