Man*_*tra 1 javascript syntax square-bracket
我试图理解点和方括号表示法之间的区别。在查看 SO 和其他一些网站上的各种示例时,我遇到了这两个简单的示例:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - helloRun Code Online (Sandbox Code Playgroud)
var user = {
name: "John Doe",
age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);Run Code Online (Sandbox Code Playgroud)
obj[x]如果在第三行中我将 替换为,第一个示例将返回 y 为未定义obj.x。为什么不"hello"
但在第二个示例中,表达式user[key]可以简单地替换为,user.key而不会出现任何异常行为(至少对我来说)。现在这让我很困惑,因为我最近了解到,如果我们想通过存储在变量中的名称访问属性,我们可以使用 [ ] 方括号表示法。
在点表示法中,点后面的名称是所引用的属性的名称。所以:
var foo = "bar";
var obj = { foo: 1, bar: 2 };
console.log(obj.foo) // = 1, since the "foo" property of obj is 1,
// independent of the variable foo
Run Code Online (Sandbox Code Playgroud)
但是,在方括号表示法中,所引用的属性的名称是 方括号中的值:
var foo = "bar";
var obj = { foo: 1, bar: 2 };
console.log(obj[foo]) // = 2, since the value of the variable foo is "bar" and
// the "bar" property of obj is 2
console.log(obj["foo"]) // = 1, since the value of the literal "foo" is "foo" and
// the "foo" property of obj is 1
Run Code Online (Sandbox Code Playgroud)
换句话说,点表示法obj.foo始终等价于obj["foo"],而obj[foo]取决于变量 的值foo。
在您问题的具体情况下,请注意点表示法和方括号表示法之间的区别:
// with dot notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;
obj.key = value; // referencing the literal property "key"
console.log(obj) // = { name: "John Doe", age: 30, key: 60 }
// with square bracket notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;
obj[key] = value; // referencing property by the value of the key variable ("age")
console.log(obj) // = { name: "John Doe", age: 60 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1509 次 |
| 最近记录: |