我在思考如何在不立即访问该对象的情况下正确更改对象的引用时遇到一些困难。考虑以下代码。是否可以在不直接设置的情况下更改颜色数组的值?
//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;
我知道引用只是从一个数组指向另一个数组。但除了上面展示的方法之外,我想不出其他方法。
欢迎任何想法或建议。
最佳答案
线路
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');
现在回到颜色
范围内,
console.log(colors); // ['white']
关于Javascript 引用指针帮助/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764383/