你list
变量将是私有的f()
除非你做的两件事情之一。
第一个,你可以尝试返回list
从f()
,这样你就可以得到你需要的属性。
function f() {
var list = [{name: 'test'}, {name: 'test2'}];
return list;
}
var f = f();
f[0] // {name: 'test'};
f['test'] // will return undefined; we'll come back to this
二,我认为这个选项也可能是你在找什么,你标有“空中接力”的问题,你可以做f()
一个构造函数:
function f() {
this.list = [{name: 'test'}, {name: 'test2'}];
}
var f1 = new f();
f1['list'][0] // {name: 'test'};
f1.list[0] // will also return {name: 'test'};
f1.list['test'] // still will return undefined...
.. 。
您将无法使用['test']
或['test2']
访问值的原因是因为它们是您的值,而通常值是我们想要在使用该键的对象(在本例中为['name']
或.name
)。所以你可能想要的是这样的:
f1.list[0].name // will return 'test'
f1.list[1].name // will return 'test2'
希望这会消除混乱。
你必须为此使用和实现一个单独的get()方法。 – Sirko 2013-02-17 10:39:58
如果'var list = [{name:'test'},{name:0}];''f [0]'会返回什么? – dfsq 2013-02-17 10:41:08
@dfsq它不应该发生,但万一它应该返回{name:'test'} – 2013-02-17 10:43:48