2

我在思考如何正确更改对象的引用而不立即访问该对象时遇到了一些困难。考虑以下代码。是否可以在不直接设置的情况下更改颜色数组的值?

//Add some colors
var colors = [];
colors.push('red');
colors.push('yellow');

//Create a reference to colors
var reference = {};
reference.colors = colors;

//Add another array of colors
var colors2 = [];
colors2.push('white');

//Change reference to point to colors2
reference.colors = colors2;

console.log(reference.colors);
console.log(colors); //Would like it to log 'white'

尽量避免编写以下代码。

colors = colors2;

我知道引用只是从一个数组指向另一个数组。但是除了上面显示的之外,我想不出一种方法来做到这一点。

欢迎任何想法或建议。

http://jsfiddle.net/Pwqeu/

4

2 回答 2

2

线

reference.colors = colors2;

意味着您可以访问reference.colors,即使您无权访问colors,对吗?所以而不是

var colors2 = [];
// etc

var colors2 = reference.colors;
// modify to your desired array
colors2.length = 0; // "reset" it
colors2.push('white');

现在回到范围内colors

console.log(colors); // ['white']
于 2013-07-20T16:51:14.097 回答
0

我相信保罗回答了你的问题,所以我只是试图分解你最初必须进一步帮助你的东西。变量不引用其他变量,它们引用变量指向的对象。

var colors = [];  // colors points to an Array Object
colors.push('red'); 
colors.push('yellow');

//Create a reference to colors
var reference = {};         // reference points to a new Object
reference.colors = colors;  // reference.colors now points to the array Object colors points to.

//Add another array of colors
var colors2 = [];          // colors2 points to new Array Object
colors2.push('white');

//Change reference to point to colors2
reference.colors = colors2;   // this statement points reference.colors to the Array Object colors2 points to. So now you will not have access to the Array object colors pointed to.

console.log(reference.colors);
console.log(colors); //Would like it to log 'white'
于 2013-07-20T17:02:12.067 回答