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

javascript - 如何将键/值对添加到JavaScript对象?(How can I add a key/value pair to a JavaScript object?)

Here is my object literal:

(这是我的对象文字:)

var obj = {key1: value1, key2: value2};

How can I add {key3: value3} to the object?

(如何向对象添加{key3: value3} ?)

  ask by James Skidmore translate from so

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

1 Reply

0 votes
by (71.8m points)

There are two ways to add new properties to an object:

(有两种向对象添加新属性的方法:)

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation: (使用点表示法:)

obj.key3 = "value3";

Using square bracket notation: (使用方括号表示法:)

obj["key3"] = "value3";

The first form is used when you know the name of the property.

(当您知道属性名称时,将使用第一种形式。)

The second form is used when the name of the property is dynamically determined.

(动态确定属性名称时,使用第二种形式。)

Like in this example:

(像这个例子:)

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

(可以使用以下任意一种来构造真实的 JavaScript数组:)

The Array literal notation: (数组文字表示法:)

var arr = [];

The Array constructor notation: (数组构造器符号:)

var arr = new Array();

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

...