我有一个JavaScript对象,如下所示:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

我如何循环遍历p的所有元素(p1、p2、p3…)并获取它们的键和值?


当前回答

最接近python的enumerate函数的解决方案:

for key, value in enumerate(object):
    # Do something

是Object.entries()和for of循环的组合:

for(let [key, value] of Object.entries(object)) {
    // Do something
}

let对象={key1:“value1”,key2:“value2”,key3:“value3”,key4:“value4”,key5:“value5”};for(let[key,value]of Object.entries(Object)){console.log(`${key}->${value}`);}

其他回答

如果有人需要使用条件循环遍历arrayObjects:

var arrayObjects=〔{“building”:“A”,“status”:“good”},{“building”:“B”,“status”:“恐怖”}〕;for(var i=0;i<arrayObjects.length;i++){console.log(arrayObjects[i]);for(arrayObjects[i]中的键){if(key==“status”&&arrayObjects[i][key]==“good”){console.log(key+“->”+arrayObjects[i][key]);}其他{console.log(“未找到任何内容”);}}}

这是如何循环javascript对象并将数据放入表中的。<body><脚本>函数createTable(objectArray,fields,fieldTitles){let body=document.getElementsByTagName('body')[0];let tbl=document.createElement('table');let thead=document.createElement('head');let thr=document.createElement('tr');for(objectArray[0]中的p){let th=document.createElement('th');th.appendChild(document.createTextNode(p));thr.appendChild(th);}thead.appendChild(thr);tbl.appendChild(thead);let tbdy=document.createElement('tbody');let tr=document.createElement('tr');objectArray.forEach((对象)=>{设n=0;let tr=document.createElement('tr');for(objectArray[0]中的p){var td=document.createElement('td');td.appendChild(document.createTextNode(object[p]));tr.appendChild(td);n++;};tbdy.appendChild(tr);});tbl.appendChild(tbdy);body.appendChild(待定)返回tbl;}创建表格([{name:“香蕉”,价格:“3.04”},//k[0]{name:“Orange”,价格:“2.56”},//k[1]{name:“苹果”,价格:“1.45”}])</script>

如果还想迭代非可枚举财产,可以使用Object.getOwnPropertyNames(obj)返回直接在给定对象上找到的所有财产(可枚举或不可枚举)的数组。

var obj=对象.创建({}{//不可枚举属性获取食物:{value:函数(){return this.foo;},可枚举:false}});obj.foo=1;//可枚举属性Object.getOwnPropertyNames(obj).forEach(函数(名称){document.write(name+':'+obj[name]+'<br/>');});

在ECMAScript 5下,可以组合Object.keys()和Array.protocol.forEach():

var obj = { first: "John", last: "Doe" };

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

ECMAScript 6添加了。。。第页,共页:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ECMAScript 8添加了Object.entries(),避免了查找原始对象中的每个值:

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

你可以组合。。。of、destructuring和Object.entries:

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

Object.keys()和Object.entries()以与for相同的顺序迭代财产。。。但忽略原型链。只迭代对象自己的可枚举财产。

当对象实现.next()方法时,它将成为迭代器

常量james={name:“James”,高度:`5'10“`,重量:185,[符号迭代器](){让财产=[]for(let key of Object.keys(james)){财产推送(键);}索引=0;返回{下一个:()=>{let键=财产[索引];let value=this[key];让done=索引>=属性.length-1;索引++;返回{钥匙价值完成};}};}};constiterator=james[Symbol.iiterator]();console.log(迭代器.next().value);//'詹姆斯console.log(迭代器.next().value);//`5'10`console.log(迭代器.next().value);//185