在Angular/JavaScript中result.id和result[';id';]之间的差异?

在Angular/JavaScript中result.id和result[';id';]之间的差异?,javascript,angular,Javascript,Angular,我想知道在Angular/JavaScript中result.id和result['id']之间有什么区别? 如果我是类型: getId(){ this.service.getId().subscribe( result=>{ var i = result.id; }//this... ) } …有时编译器用红色下划线装饰result.id(错误),然后我将其更改为: getId(){ this.service.getId().subscribe( resul

我想知道在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,却看不到任何错误

请注意,结果类型是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
其次,方括号表示法在处理以可预测方式变化的属性名称时非常有用:

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

这取决于您使用的是对象还是数组。点表示法在使用对象时起作用。如果使用方括号有时会引发错误。

两种情况下的值相同,@Suneet Bansal正确指出了差异。
在您的情况下,可能是linter导致了错误。

从代码的角度来看,没有任何问题。无论您使用的编辑器是什么,如果您不想将
result.id
result['id']
标记为对任何对象的错误“cast”,它们都是相同的:
subscribe((res:any)=>{let i=result.id})
:注意:请尝试使用“let”,而不是“var”来定义变量,否则变量可以在应用程序中传播