我有

var myFirstArray = [{letter: 'a'}, {letter: 'b'}, {letter: 'c'}];


我想引用myFirstArray,所以我这样做:

var mySecondArray = myFirstArray;


推送,剪接,修改myFirstArray中的元素将显示在mySecondArray中,但是如果我想将该数组重置为其他内容:

myFirstArray = [];


要么

myFirstArray = someOtherData;


我的参考资料丢失了。我理解为什么会这样,但是我希望mySecondArray随时指向myFirstArray指向的内容。最好的方法是什么?

我的解决方法包括:

// Just empty the array and push it:
while (myFirstArray.length) myFirstArray.pop();
for (var x in data) myFirstArray.push(x);

// Or put the array in an object:
var viewBag = {};
viewBag.myFirstArray = [...];

var mySecondArray = viewBag.myFirstArray;


我不喜欢这两种选择:(

编辑:考虑另一种情况:

function doSomethingToMyArray (theArray) {
  // Say I get new data that will be formatted the way I want it to be
  // Shouldn't I be allowed to do this?

  var myNewData = [{ letter: 'd' }];
  theArray = myNewData;
}

var myFirstArray = [{letter: 'a'}, {letter: 'b'}, {letter: 'c'}];

doSomethingToMyArray (myFirstArray);

// At this point, myFirstArray will still be a, b, c instead of d

最佳答案

为什么在设置myFirstArray时不设置mySecondArray?

下面的语法是一个快速设置变量的好技巧:

var mySecondArray, myFirstArray;

mySecondArray = myFirstArray = ["somevalue"];


在JavaScript中,将myFirstArray设置为[],然后将mySecondArray设置为myFirstArray时,它不会引用第一个变量,但是两个变量都将引用相同的实际数组。

10-07 17:22