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

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

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


当前回答

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

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

安装:npm i一元对象

该库还包括以下方法:

地图滤器每一个一些

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

其他回答

通过带有forEach()的原型,它应该跳过原型链财产:

Object.prototype.each = function(f) {
    var obj = this
    Object.keys(obj).forEach( function(key) { 
        f( key , obj[key] ) 
    });
}


//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3

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

因为提问者的[第二个目标是循环一些键值对],最后不要寻找循环。

var p ={"p1":"value1","p2":"value2","p3":"value3"};
if('p1' in p){
  var val=p['p1'];
  ...
}

我会这样做,而不是在每个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");
}

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