我想知道 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 而看不到任何错误。
Note that the result type is any !!!
所以我对两个案例有点困惑。我错过了什么吗?
无论如何,谢谢!
最佳答案
方括号表示法允许使用不能与点表示法一起使用的字符:
var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax
其次,在处理以可预测方式变化的属性名称时,方括号表示法非常有用:
for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}
综述:
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
关于javascript - Angular/JavaScript 中 result.id 和 result ['id' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263221/