点和方括号表示法 [英] Dot and Square Bracket Notation

查看:173
本文介绍了点和方括号表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:

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 。为什么不你好

The first example returns y to be undefined if in third line I replace the obj[x] with obj.x. Why not "hello"

但在第二个例子中表达式 user [key] 可以简单地替换为 user.key 而不会出现任何异常行为(至少对我而言) 。
现在这让我感到困惑,因为我最近了解到,如果我们想要按存储在变量中的名称访问属性,我们使用[]方括号表示法。

But in the second example the expression user[key] can simply be replaced with user.key without any anomalous behavior (at-least to me). Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.

推荐答案

在点表示法中,点后面的名称是被引用属性的名称。所以:

In dot notation, the name after the dot is the name of the property being referenced. So:

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

但是,在方括号表示法中,被引用的属性的名称是,无论是什么在方括号中:

However, in square-bracket notation, the name of the property being referenced is the value of whatever is in the square brackets:

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

In other words, dot-notation obj.foo is always equivalent to obj["foo"], while obj[foo] depends on the value of the variable foo.

在你的特定情况下问题,请注意点表示法和方括号表示法之间的区别:

In the specific case of your question, note the differences between dot notation and square-bracket notation:

// 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 }

这篇关于点和方括号表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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