[英]do javascript arrays clone
I have two arrays as parameters and need to add each element from the add
array to the main
array, sort the main
, then remove that element, and repeat (add the next element of add
array to main
array).我有两个 arrays 作为参数,需要将add
数组中的每个元素添加到main
数组中,对main
进行排序,然后删除该元素,然后重复(将add
数组的下一个元素添加到main
数组)。
function twoArrays(main, add) {
var tempArr =[];
for(var i=0; i<main.length; i++){
tempArr.push(main[i]);
}
for(var i=0; i<add.length; i++){
main.push(add[i]);
main = main.sort(function(a, b){return b - a});
console.log(main);
main = [];
main = tempArr;
}
}
var main =[ 100, 100, 50, 40, 40, 20, 10 ]
var add = [99, 44,33,22,9]
twoArrays(main, add);
My problem is this statement main = tempArr;
我的问题是这个语句main = tempArr;
is not working the way I think it should.没有按照我认为的方式工作。 I expect to delete main ( main = [];
), and then populate main with tempArr
( main = tempArr;
).我希望删除 main ( main = [];
),然后用tempArr
( main = tempArr;
) 填充 main。 However, I get the previous main, with add
items in it, notice the 99, 44, 33, 22 as follows但是,我得到了以前的 main,其中add
了项目,请注意 99、44、33、22 如下
100,100,99,50,40,40,20,10
100,100,50,44,40,40,20,10
100,100,50,44,40,40,33,20,10
100,100,50,44,40,40,33,22,20,10
100,100,50,44,40,40,33,22,20,10,9
As others have said, you're losing reference to the original main when you do main = []
.正如其他人所说,当您执行main = []
时,您将失去对原始 main 的引用。 If you want to reset the array, and do a new transformation (add an element from add
to main
, sort, then reset), try this instead:如果要重置数组并进行新的转换(将元素从add
到main
,排序,然后重置),请尝试以下操作:
function twoArrays(main, add) { for(var i=0; i<add.length; i++){ let clone = [...main]; clone.push(add[i]); clone.sort(function(a, b){return b - a}); console.log(clone); } } const main =[ 100, 100, 50, 40, 40, 20, 10 ] const add = [99, 44,33,22,9] twoArrays(main, add);
When you do main = tempArr;
当你做main = tempArr;
main and tempArr both point to the same array. main 和 tempArr 都指向同一个数组。 To copy the tempArr in main, instead of main = []; main = tempArr;
在 main 中复制 tempArr,而不是main = []; main = tempArr;
main = []; main = tempArr;
do main = [..tempArr];
main = [..tempArr];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.