Javascript引用指针帮助/解释



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

//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/

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']

我相信Paul回答了你的问题,所以我只想试着分解一下你最初需要做什么来进一步帮助你。变量不引用其他变量,而是引用变量指向的对象。

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'

最新更新