Angular/JavaScript中result.id和result ['id']之间的区别? [英] Difference between result.id and result['id'] in Angular/JavaScript?

查看:60
本文介绍了Angular/JavaScript中result.id和result ['id']之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Angular/JavaScript中result.id和result ['id']之间有什么区别? 如果我输入:

I'm wonder what is difference between result.id and result['id'] in Angular/JavaScript ? If i'm type :

getId(){
  this.service.getId().subscribe(
    result=>{ var i = result.id; }//this...
  )
}

...有时,编译器用红色下划线(错误)修饰result.id,然后将其更改为:

...sometimes the compiler decorate result.id with red underline (error) then i change it to :

getId(){
  this.service.getId().subscribe(
    result=>{ var i = result['id']; }//with this
  )
}

装饰消失了.但是有时我可以写result.id却看不到任何错误.

the decoration disappear. But sometimes i can write result.id and not see any errors.

请注意,结果类型为任何 !!!!

Note that the result type is any !!!

所以我对2个案例有些困惑.我错过了什么吗?

So i'm confused a little with 2 cases. Did i miss something ?

还是谢谢!

推荐答案

方括号表示法允许使用点符号不能使用的字符:

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

不能与点符号一起使用的字符的另一个示例是本身包含点的属性名称.

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

例如,一个json响应可以包含一个名为bar.Baz.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

这篇关于Angular/JavaScript中result.id和result ['id']之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆