使用'[]'表示法访问javascript对象成员而不是点符号的原因是什么? [英] What is reason of using ' [ ] ' notation to access javascript object members instead of dot notation?
问题描述
可能重复:
JavaScript属性访问:点符号与括号?
我现在正在阅读一些开源的javascript项目代码,我发现他们有时会访问像 person.name
这样的对象属性,但有时它们会像<$ c $一样访问C>人[ '名称'] 。
I am now reading some of open source javascript project codes and i see that sometimes they access object property like person.name
but sometimes they access like person['name']
.
对我而言,点符号与其他符号相当清楚。点符号很容易写和读,但在源代码中我看到它们有时使用点符号有时[]括号符号,我试图理解它的原因是什么。
For me dot notation is so much clear against other. Dot notation is easy to write and read but in source code i see that they are sometimes used dot notation sometimes [] braces notation and i am trying to understand what is the reason of it.
这可能是什么原因?
推荐答案
首先它可以是动态的字符串:
First it can be dynamic with a string:
var key = 'name';
person[key];
其次,它还支持其他不受支持的符号
Second, it also supports other symbols that aren't supported
var key = 'first-name';
person[key];
这篇关于使用'[]'表示法访问javascript对象成员而不是点符号的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!