[英]How to check in an object whether its has the key or not?
var object = [{key1:'value',key2:'value2'},{'key1:'value',key2:'value2}]
for (var key in object)
{
if(!object.hasOwnProperty(key)){continue;}
Why do we get error?为什么我们会出错? Am i checking the right way.
我检查的方法是否正确。
I get an error cannot call hasOwnProperty in an Object - TypeError
我收到一个
error cannot call hasOwnProperty in an Object - TypeError
object
is not defined. object
未定义。 Check this revision:检查此修订:
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 */
}
}
}
}
Is your for-loop correct?你的for循环正确吗? Try this
尝试这个
for (var key in array)
{
...
You have not defined object
in your for loop.您尚未在 for 循环中定义
object
。 Your array of objects above is named array
.上面的对象数组名为
array
。
for (var key in array) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.