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

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

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


当前回答

在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相同的顺序迭代财产。。。但忽略原型链。只迭代对象自己的可枚举财产。

其他回答

这是如何循环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>

你可以使用我的库monadic对象来实现这一点。它的设计目的是简化对象修改并使其行为类似于数组:

p.forEach((key, value) => console.log(key, value))

安装:npm i一元对象

该库还包括以下方法:

地图滤器每一个一些

有关更多信息,请参阅README!

我会这样做,而不是在每个for…中检查obj.hasOwnerProperty。。。在循环中。

var obj = {a : 1};
for(var key in obj){
    //obj.hasOwnProperty(key) is not needed.
    console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
    throw new Error("Please don't extend the native object");
}

您必须使用for in循环

但在使用这种循环时要非常小心,因为这将沿着原型链循环所有财产。

因此,在循环中使用for时,请始终使用hasOwnProperty方法来确定迭代中的当前属性是否真的是要检查的对象的属性:

for (var prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}
Object.entries(myObject).map(([key, value]) => console.log(key, value))

你可以这样试试。myObject将是{name:“”,phone:“”}等等,这将生成密钥和值。所以这里的关键是名字,电话和价值就像狗,123123。

示例{name:“dog”}

这里的键是名字,值是狗。