1. 程式人生 > >javascript 對象屬性的添加,刪除,json對象和字符串轉換方法等

javascript 對象屬性的添加,刪除,json對象和字符串轉換方法等

star font style strong 字符串轉換 定義 obj tarray def

1:動態添加 對象屬性

var obj = new Object();

console.log (obj.username);

obj.username = "haha";

console.log (obj.username);

//undefined

//haha

[]”表示。寫成 obj["username"] = "haha";

var obj = new Object();

console.log (obj.username);

obj["username"] = "haha";

console.log (obj.username);

//undefined

//haha

還可以直接定義

var obj = {username:"haha", password:"123"};

console.log(obj.username);

console.log(obj.password);

//haha

//123

2:刪除屬性,使用 delete

var obj = new Object();

obj["username"] = "haha";

console.log (obj.username);

delete obj.username;

console.log (obj.username);

//haha

//undefined

3:修改原屬性,增加新屬性

var json = {

"age":24,

"name":"haha"

};

//修改Json中的

age

json["age"] = 30;

console.log(json.age);

//30

//增加Json中的sex

json["sex"] = "w";

console.log(json.sex);

//w

4:Json對象與Json字符串互轉

JSON.parse(jsonstr); //可以將json字符串轉換成json對象

var jsObj = {};
jsObj.testArray = [1,2,3];
jsObj.name = ‘CSS3‘;
jsObj.date = ‘2017‘;
console.log(jsObj)
console.log(typeof(jsObj));
var str = JSON.stringify(jsObj);
var str1 = JSON.parse(str);
console.log(str)
console.log(typeof(str));
console.log(str1)
console.log(typeof(str1));
//Object {testArray: Array[3], name: "CSS3", date: "2017"}
//object
// {"testArray":[1,2,3],"name":"CSS3","date":"2017"}
// string
//Object {testArray: Array[3], name: "CSS3", date: "2017"}
// object

JSON.stringify(jsonobj); //可以將json對象轉換成json字符串

var jsObj = {};
jsObj.testArray = [1,2,3];
jsObj.name = ‘CSS3‘;
jsObj.date = ‘2017‘;
console.log(jsObj)
console.log(typeof(jsObj));
var str = JSON.stringify(jsObj);
console.log(str)
console.log(typeof(str));
//Object {testArray: Array[3], name: "CSS3", date: "2017"}
// object
// {"testArray":[1,2,3],"name":"CSS3","date":"2017"}
//string

javascript 對象屬性的添加,刪除,json對象和字符串轉換方法等