目 录CONTENT

文章目录

JS中操作object的一些方法

cplinux98
2022-08-30 / 0 评论 / 0 点赞 / 47 阅读 / 267 字 / 正在检测是否收录...

00:文章简介

记录一下js中操作object的一些方法

01:创建

var o = new Object();

02:增加元素

var o = new Object();
o['name'] = 'xiaoli'
console.log(o.name);
// xiaoli

03:删除元素

var o = new Object();
o['name'] = 'xiaoli'
o['age'] = 18
console.log(o.name);
// xiaoli
delete o.name
console.log(o.name);
// undefined

o['age'] = undefined
console.log(o.age)

04:获取元素value

var o = new Object();
o['name'] = 'xiaoli'
console.log(o.name);
// xiaoli
console.log(o['name']);
// xiaoli

05:修改

var o = new Object();
o['name'] = 'aaaaa'
console.log(o.name);
// aaaaa

o['name'] = 'bbbbb'
console.log(o['name']);
// bbbbb

o.name = 'ccccc'
console.log(o.name);
// ccccc

06:遍历元素

var o = new Object();
o['name'] = 'xiaoli'
o['age'] = 18

for (var i in o) {
    console.log(i, o[i])
}
// name xiaoli
// age 18

// 遍历所有元素的key

console.log(Object.keys(o))
// [ 'name', 'age' ]


// 遍历所有元素的值

console.log(Object.values(o))
// [ 'xiaoli', 18 ]


// 获取所有元素的key和value
Object.getOwnPropertyNames(o).forEach(function(key){
    console.log(key+ '---'+o[key])
})

// name---xiaoli
// age---18


0

评论区