我想知道 Angular/JavaScript 中的 result.id 和 result['id'] 有什么区别?
如果我输入:
getId(){
this.service.getId().subscribe(
result=>{ var i = result.id; }//this...
)
}
...有时编译器用红色下划线装饰 result.id (错误)然后我将其更改为:
getId(){
this.service.getId().subscribe(
result=>{ var i = result['id']; }//with this
)
}
装饰消失。但有时我可以写 result.id 而看不到任何错误。
请注意,result类型是any !!!
所以我对两个案例有点困惑。我错过了什么 ?
不管怎么说,还是要谢谢你!
方括号表示法允许使用不能与点表示法一起使用的字符:
var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax
其次,在处理以可预测的方式变化的属性名称时,方括号表示法非常有用:
for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}
Roundup:
1. Dot notation is faster to write and clearer to read.
2. Square bracket notation allows access to properties containing special characters and selection of properties using variables
不能与点表示法一起使用的字符的另一个示例是本身包含点的属性名称。
例如,json 响应可能包含一个名为bar.Baz.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)