繁体   English   中英

Javascript _ 点符号和括号符号

[英]Javascript _ Dot notation and Bracket Notation

我有两个问题如下。 谁能帮忙解释一下? 如果有素材来源,也请帮忙提供链接。 谢谢你!

问题1:为什么下面2个输出不同。 一个是37。另一个是40。我认为两个输出都应该是40。请帮助解释原因。


let me = {
    firstName: 'Terry',
    gender: 'Male',
    age: 37
};

let selection = 'age';
me.selection = 40;

console.log('Bracket Notation of selection: ', me[selection]);  // output: 37
console.log('Dot Notation of selection: ', me.selection); // out put: 40

问题2:这次,我从点号(me.selection = 40)改为括号号(me[selection] = 40)。 第一个 output 从 37 变为 40。第二个 output 从 40 变为未定义。 请帮忙解释原因。

let me = {
    firstName: 'Terry',
    gender: 'Male',
    age: 37
};

let selection = 'age'
me[selection] = 40; //change from dot notation (me.selection = 40) to bracket notation (me[selection] = 40)

console.log('Bracket Notation of selection: ', me[selection]);  // output: 40
console.log('Dot Notation of selection: ', me.selection); // output: undefined

问题1的答案:

me[selection]等同于说me["age"] ...也就是 37

me.selection相当于说me["selection"] ... 所以答案是 40

问题2的答案:

me[selection] = 40; 相当于说me["age"] = 40

所以当你之后在 console.log 中执行me.selection时,它返回undefined因为它找不到selection

当你说me[selection]它返回 40 因为你真的在问me["age"] .. 而这次你指的是变量“selection”而不是关键选择

由于 selection 等于 'age' me[selection] 等于 me['age'] (或 me.age),它是 37 但被重新分配为 40

me.selection 等同于 me['selection'] 不存在于 object

当您使用点表示法时,您是直接给 JavaScript 属性名称,但是当您使用括号表示法中的变量来访问属性值时, JavaScript 关心变量的值,而不是它的名称

机制很简单

点符号:me.selection =>>>> js直接查找属性名称“selection”。

括号表示法:me[selection] =>>> js 查找 selection 的值,它等于“age”,查找属性名称 age。

这在哪里有用? 有时您想根据代码中的一些其他常量或变量创建属性

在这里,您根据等于 10 的常量创建属性:

let neededProperties=10
for (let i=0;i<neededProperties;i++) {
    neededProperties["prop"+i]=i
}

属性访问器使用点表示法或括号表示法提供对对象属性的访问。 在点表示法中,我们必须给出访问其值的确切属性,在方括号表示法中,我们传递具有属性名称的动态值来访问 object 的属性值。

所以,解释:你有一个名为 me 的 object,它具有不同的属性,还有一个带有选择的 vaiable 因此,将使用点符号访问值,即 me.selection 你直接从 object 属性中获得值,即 40。

使用方括号表示法,即 me[selection],在这种情况下,将使用选择变量,并且此变量将被替换为它的值,如 me['age']。 因此,您从具有属性名称 age 的 object 中获取值。

希望您了解两者的逻辑和原因,并找到您的两个问题的答案,并在此处查看详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM