点和方括号表示法



我试图理解点和方括号符号之间的区别。在SO和其他一些网站上浏览各种示例时,我遇到了这两个简单的例子:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

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]);

第一个示例返回 y 未定义,如果在第三行中我将obj[x]替换为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

但是,在方括号表示法中,被引用的属性的名称是方括号中任何内容的值:

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

换句话说,点表示法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 }

从 JavaScript 对象访问/创建属性可以通过两种方式完成

  1. 使用表示法
  2. 使用方括号表示法

每当某些属性未定义时,即对象中不存在并且您尝试访问它,您将得到undefined(显然,因为它不存在)。

因此,在第一个示例中,您正在访问一个属性,在第二个示例中,您正在创建一个属性。因此,替换表示法不会影响第二个示例中的代码。

最新更新