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
229 views
in Technique[技术] by (71.8m points)

arrays - Object properties in JavaScript


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

1 Reply

0 votes
by (71.8m points)

In JavaScript, [] is used to determine an Array literal, but is also one of the ways to call Object keys, hence your confusion.

const myArray = []; // Returns an empty array
const someObjectValue = myObject["myKey"] // returns the value of an object's key

Please note you can also fetch an object value by using dot instead of brackets:

// They are the same thing.
const value = myObject["myKey"];
const sameValue = myObject.myKey;

They're basically two different ways of achieving the same thing.

There is one difference, thought. With brackets you can assign otherwise non-allowed keys to objects.

Example:

const myObject = {};

// Set
myObject.0 = "Hello!"; // throws error
myObject[0] = "Hello!"; // works!

myObject.some-key = "Hello!"; // throws error
myObject["some-key"] = "Hello!"; // works!

// Get
const value = myObject.0; // throws error
const value = myObject[0]; // works!

const value = myObject.some-key; // throws error
const value = myObject["some-key"]; // works!

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

1.4m articles

1.4m replys

5 comments

56.9k users

...