var object = [{key1:'value',key2:'value2'},{'key1:'value',key2:'value2}]
for (var key in object)
{
if(!object.hasOwnProperty(key)){continue;}
为什么会出错?我在检查正确的方法吗?
我得到一个
error cannot call hasOwnProperty in an Object - TypeError
最佳答案
未定义object
。检查此修订:
var myarr = [{key1:'value',key2:'value2'},{key1:'value',key2:'value2'}];
//renamed to myarr to avoid confusion - and removed typos from your code.
//myarr is now an array of objects
//loop through myarr
for (var i=0;i<myarr.length;i=i+1){
//check if the element myarr[i] is indeed an object
if (myarr[i].constructor === Object) {
//loop through the object myarr[i]
for (var key in myarr[i]) {
//notice the removal of !
if(myarr[i].hasOwnProperty(key)){
/* do things */
}
}
}
}
关于javascript - 如何检查对象是否有 key ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6747208/