我正在循环浏览一个列表,向其中的每个项目添加一个新字段,如下所示:
for (var i = 0; i < returnList.length; i++) {
returnList[i].eligible = true;
};
那么如果我这样做:
for (var i = 0; i < returnList.length; i++) {
console.log(returnList.eligible);
};
它多次返回“true”。
但是如果我这样做:
console.log(returnList);
然后它返回(我只给出其中一个对象的示例):
{ _id: 557ff7dab10a9e8029cf9baa,
WGS84:{ longitude: 0.028586996883792574,
latitude: 51.363584078860356 },
free: false,
approved: true,
organisationName: 'Test Organisation',
__v: 0,
polygonLineCoordinates: [],
organisationLocation: { postCode: 'BR2 6BP' },
opportunities: [],
events: [],
supportAreas: [] }
这显然没有符合条件的元素。我只是想知道发生了什么!
亚当
最佳答案
您可以定义一个非enumerable属性(property)。最简单的解决方案是使用 Object.defineProperty
:
var obj = {};
obj.someProp = true;
Object.defineProperty(obj, 'eligible', {writable:true});
obj.eligible = true;
console.log(obj.eligible); // logs true
for (var k in obj) {
console.log(k); // only logs "someProp"
}
var obj = {};
obj.someProp = true;
Object.defineProperty(obj, 'eligible', {writable:true});
obj.eligible = true
document.body.appendChild(document.createElement('pre')).innerHTML = "obj.eligible = "+obj.eligible;
console.log(obj.eligible); // logs true
for (var k in obj) {
console.log(k); // only logs "someProp"
}
document.body.appendChild(document.createElement('pre')).innerHTML = JSON.stringify(obj)
关于javascript - 添加属性,打印对象时不会显示该属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30889294/