如何在javascript中物件增加key和value,類似array push的概念。

最近比較常接觸javascript,太久沒碰真的很多東西都不熟阿!

比如說array和object的定義宣告與使用,真的搞得一頭霧水。

 

轉自 http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object

--

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

 

real JavaScript array can be constructed using either:

 

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

 

--

文章標籤
全站熱搜
創作者介紹
創作者 dizzy03 的頭像
dizzy03

碎碎念

dizzy03 發表在 痞客邦 留言(0) 人氣(1)