2013-02-17 86 views
0

我发现没有办法做到这一点。不过,谢谢大家! In javascript, can I override the brackets to access characters in a string?更改默认数组类型getter Javascript

我有这样的事情:

function f() { 
    var list = [{name: 'test'}, {name: 'test2'}]; 
} 

而且我想从该列表是这样的函数内部获取属性,我觉得有一些覆盖默认的[]的方法,但我真不不知道该找什么。

f[0] // {name: 'test'} 
f['test2'] // {name: 'test2'} 
+0

你必须为此使用和实现一个单独的get()方法。 – Sirko 2013-02-17 10:39:58

+0

如果'var list = [{name:'test'},{name:0}];''f [0]'会返回什么? – dfsq 2013-02-17 10:41:08

+0

@dfsq它不应该发生,但万一它应该返回{name:'test'} – 2013-02-17 10:43:48

回答

1

list变量将是私有的f()除非你做的两件事情之一。

第一个,你可以尝试返回listf(),这样你就可以得到你需要的属性。

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' 

希望这会消除混乱。

+0

我已经知道解决我的问题的这些方法,但他们不是我正在寻找的。无论如何,谢谢你,不幸的是,我认为不可能按照我的想法解决问题。 – 2013-02-17 10:50:15

+0

代码的目的是什么?我可能会帮助... – guypursey 2013-02-17 10:51:20

+0

我在写一个使用webSocket与服务器交互的客户端。问题是我有一个名为ChannelList的对象的通道列表(它类似于IRC)。该对象里面有一个列表channels = []和一些方法。下面是一段代码,如果有帮助的话:http://jsbin.com/isejuh/1/edit – 2013-02-17 10:56:27

0

只要使用的不是数组对象:

var byname = { 
    "test": {name: 'test'}, 
    "test2": {name: 'test2'} 
}; 
// bracket notation: 
byname["test2"] // {name: 'test2'} 
// dot notation: 
byname.test // {name: 'test'} 

既然你说你永远不会通过索引来访问结构,这将是确定使用无序的键 - 值映射结构。为了节省打字的时间,你也可以从你的数组中动态地创建这个对象:

var list = [{name: 'test'}, {name: 'test2'}]; 

var byname = {}; 
for (var i=0; i<list.length; i++) 
    byname[list[i].name] = list[i];