问题描述
下面是我的小提琴: http://jsfiddle.net/sepoto/Zgu9J/1/一>
我开始有反函数:
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
//I tried changing the return value to
//return ret.slice(0) which has no effect on making
//an independent copy
return ret;
}
第二个数组我做pointOrigins2不是pointOrigins1的独立副本。换句话说修改pointOrigins2还修改pointOrigins1这不是我所需要达到的。从我在计算器上读我已经尝试了几个选项,比如使用切片或使用for循环然而似乎没有什么可又工作,所以我做了一个小提琴。
The second array I make pointOrigins2 is not an independent copy of pointOrigins1. In other words modifying pointOrigins2 is also modifying pointOrigins1 which is not what I need to achieve. From my reading on StackOverflow I have tried a few options such as using slice or using a for loop however nothing seems to be working yet so I made a fiddle.
有没有一种方法,使扭转数组的独立副本?
Is there a way to make an independent copy of the reversed array?
推荐答案
您正在一个新的独立数组,但你是不是做了填补你的阵列项目的独立副本。你需要做的是这样的:
You are making a new independent array, but you are not making independent copies of the items that fill your arrays. You need to do something like:
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push({
positionx: input[i].positionx,
positiony: input[i].positiony,
index: input[i].index
});
}
return ret;
}
让你产生新的对象(具有相同的属性),以及新的数组。
so that you are generating new objects (with the same properties) as well as the new array.
这篇关于制作逆转阵列的独立副本在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!