Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - Dot and Square Bracket Notation

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...