![](/img/trans.png)
[英]Setting array-type syntax for mdDialog controller in Angular Material
[英]Change default array-type getter Javascript
我发现没有办法做到这一点。 但是,谢谢大家! 在javascript中,我可以覆盖方括号来访问字符串中的字符吗?
我有这样的事情:
function f() {
var list = [{name: 'test'}, {name: 'test2'}];
}
我想从该函数内的列表中获取属性,我认为有些方法可以覆盖default [],但我真的不知道要查找什么。
f[0] // {name: 'test'}
f['test2'] // {name: 'test2'}
除非您执行以下两项操作之一,否则list
变量将是f()
私有变量。
首先 ,您可以尝试从f()
返回list
,以便随后获得所需的属性。
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
其次 ,我认为此选项可能是您在用'oop'标记问题时要查找的内容,可以使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'
希望这能消除混乱。
只需使用对象而不是数组即可:
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.