javascript - Angular/JavaScript 中 result.id 和 result ['id' 之间的区别?

标签 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(
    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/

相关文章:

html - 重用具有不同输入的 Angular 组件

javascript - 使用子字符串 javascript 获取与字符串的匹配

javascript - 在 Immutable.js Map 中查找嵌套对象的最佳方法

angular - 如何在 Angular8 库中包含图标等 Assets ?

angular - 带有延迟操作符的单元测试 Observable

Angular 2使用对象名称加入对象数组

javascript - this.context 在使用 react-router 时不包含 router

javascript - Semantic-ui 什么时候需要单独导入/链接组件?

javascript - 如果不包含父 key ,则无法获取 Firebase 输出

html - Angular 8形式,ngSubmit返回空数据对象