我在如何正确更改对象的引用而不立即访问该对象时遇到了一些困难。请考虑以下代码。是否可以在不直接设置的情况下更改颜色数组的值?
//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;
我知道引用只是从一个数组指向另一个数组。但除了我上面展示的内容外,我无法想出办法。
欢迎任何想法或建议。
答案 0 :(得分:2)
该行
reference.colors = colors2;
表示即使您无法访问reference.colors
,也可以访问colors
,对吧?所以而不是
var colors2 = [];
// etc
DO
var colors2 = reference.colors;
// modify to your desired array
colors2.length = 0; // "reset" it
colors2.push('white');
现在回到colors
,
console.log(colors); // ['white']
答案 1 :(得分: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'