如何在数组中存储对变量的引用? [英] How can I store reference to a variable within an array?

查看:51
本文介绍了如何在数组中存储对变量的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将字符串映射到变量的数组.似乎该数组存储变量的当前值,而不是存储对该变量的引用.

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.

var name = "foo";
var array = [];

array["reference"] = name;

name = "bar";

// Still returns "foo" when I'd like it to return "bar."
array["reference"];

有没有办法使数组引用变量?

Is there a way to make the array refer to the variable?

推荐答案

您不能.

JavaScript 始终 按值传递.一切都是对象; var 存储指针,因此通过指针的值传递.

JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.

如果您的 name ="bar" 应该位于函数内部,则需要传递整个数组.然后,该功能将需要使用 array ["reference"] ="bar" 对其进行更改.

If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".

Btw, [] 是数组文字. {} 是对象文字.该 array ["reference"] 之所以起作用,是因为Array也是一个对象,但是array是要从基于0的索引访问的.您可能想改用 {} .

Btw, [] is an array literal. {} is an object literal. That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.

foo ["bar"] 等同于 foo.bar .如果键可以是动态键(例如 foo [bar] ),而不是与foo.bar完全不同(或者如果您要使用最小化器,例如Google的Closure Compiler),则较长的语法会更有用.

And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).

这篇关于如何在数组中存储对变量的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆