我有一个包含 JSON 值的数组
category = [ {"categoryName":"abcd","productName":"chicken biriyani","price":100,"quantity":"medium"}, {"categoryName":"biriyani","productName":"mutton biriyani","price":130,"quantity":"medium"} ]
我必须检查上述类别数组所需的参数。 所以我创建了一个必需的参数数组。 var reqarray = ['类别名称','产品名称','价格','数量'];
我创建了示例代码来检查 reqarray 的值和类别的每个值。但它不起作用
var categoryList = [ {"categoryName":"abcd","productName":"chicken biriyani","price":100,"quantity":"medium"}, {"categoryName":"biriyani","productName":"mutton biriyani","price":130,"quantity":"medium"} ];
for(var i in categoryList){
var reqarray =['categoryName','productName','price','quantity'];
for(var j in arr){
if(categoryList[i].reqarray[j]=='null' || categoryList[i].reqarray[j] == " "){
console.log("data is null");
}
else if(categoryList[i].reqarray[j] == undefined){
console.log("required parameters");
}
else{
console.log("ok");
}
}
}
}
此代码显示错误:
TypeError: Cannot read property '0' of undefined
最佳答案
可以将对象视为关联数组(也称为映射、字典、哈希、查找表)。该数组中的键是对象属性的名称。
访问属性有两种方法:点表示法和方括号表示法。
点符号:
get = object.property;
object.property = set;
使用点表示法调用方法:
document.createElement('pre');
括号符号
get = object[property_name];
object[property_name] = set;
使用方括号表示法调用:
document['createElement']('pre');
在这种情况下,文字'createElement'
是已知的,您可以使用点运算符直接访问该属性。如果 createElement
是表达式求值的结果,那么您需要使用方括号表示法,从而指示 JS 编译器首先求方括号内的内容,然后访问 处的值评估对象的属性。
var categoryList = [ {"categoryName":"abcd","productName":"chicken biriyani","price":100,"quantity":"medium"}, {"categoryName":"biriyani","productName":"mutton biriyani","price":130,"quantity":"medium"} ];
for(var i in categoryList){
var reqarray =['categoryName','productName','price','quantity'];
for(var j in reqarray){
if(categoryList[i][reqarray[j]]=='null' || categoryList[i][reqarray[j]] == " "){
console.log("data is null");
}
else if(categoryList[i][reqarray[j]] == undefined){
console.log("required parameters");
}
else{
console.log("ok");
}
}
}
关于javascript - 类型错误 : Cannot read property '0' of undefined when comparing the arrays?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128518/