在我编写的一个小程序中,我有一个包含3个子数组的数组,每个子数组包含4个对象。我将数组放入一个函数,该函数消除每个子数组中的值,直到每个子数组中只有一个对象为止,并返回一个包含最后3个剩余对象的对象。
我的问题是,无论我做什么,原始数组都会在过程中被修改。我尝试过以下方法:
var itemsArr = [[obj1, obj2, obj3, obj4], [moreObj1, moreObj2, moreObj3, moreObj4],[lastObj1, lastObj2, lastObj3, lastObj4]];
// each item in itemsArr subjarrays are objects containing name, url, and id keys.
var generateResults = function(array, num){
var arr = array.slice(); // generating copy of original array here (for some reason it isn't working
// have also tried arr = [].concat(array);
var counter = 1;
var holderObj;
var results = {
baby: null,
husband: null,
home: null
};
var tempArr;
// iterate over outer array, containing arrays in each element
var i = 0;
while (true){
if (arr[i].length === 1){
holderObj = arr.splice(i,1)[0][0];
i--; // accounting for reindexing of arr. could also iterate backwards if this doesn't work
results[holderObj.id] = holderObj;
}
if (arr[i]){
for (var j=0; j<arr[i].length; j++){
if (counter === num){
arr[i].splice(j,1);
counter = 0;
j--; // accounts for reindexing of arr[i]. Other solution would be iterating backwards
}
else{
counter ++;
}
}
}
if (results.baby !== null && results.husband !== null && results.home !== null){
break;
}
else if (i === arr.length-1){
i = -1;
}
i++;
}
return results;
}
当我调用generateResults(itemsArr,num)时,如何防止修改原始itemsArr;?
我也尝试用generateResults替换第一行 var arr = [] .concat(array);
答案 0 :(得分:0)
尝试使用Array.prototype.slice()
generateResults(itemsArr.slice(), num)
var itemsArr = [{a:1},{b:2},{c:3},{d:4}];
var itemsArrCopy = itemsArr.slice();
itemsArrCopy.splice(1,1);
console.log(itemsArr, itemsArrCopy);
答案 1 :(得分:0)
两级数组副本应该通过替换
来防止修改数组array
参数数组
var arr = array.slice();
与
var arr = [];
// ...
for(var i = 0; i < array.length; ++i)
arr[i] = array[i].slice();
发布了array
的副本使arr
和array
个不同的Array对象,但是它们的元素保持相同的数组。所以发布的代码中的arr[i].splice(j,1);
正在修改array[i]
,因为它与arr[i]