为什么以下内容会返回false
:
var o = {
a: 1,
b: 2,
c: {
d: 10,
e: 20
}
}
_.has(o, "d")
_。has()不能用于嵌套属性,即嵌套对象的属性?!
答案 0 :(得分:1)
_。has(object,key)是javascript object.hasOwnProperty(key)的快捷方式,它不是递归的。所以那不会那样工作。
虽然可以这样实现:
a = {
"a" : 1,
"b" : 2,
"c" : {
"d":4,
"e":5,
"f":{
"g":7,
"h":8
}
}
};
// hasr => has recursive
_.hasr = function(object, key){
if (_.has(object, key)){
return true;
}else{
if(object instanceof Object){
for(subobject in object){
var recursive = _.hasr(object[subobject], key)
if(recursive){
return true
}
}
}
}
return false;
};
console.log(_.hasr(a, "a")); // Return true
console.log(_.hasr(a, "b")); // Return true
console.log(_.hasr(a, "c")); // Return true
console.log(_.hasr(a, "d")); // Return true
console.log(_.hasr(a, "e")); // Return true
console.log(_.hasr(a, "f")); // Return true
console.log(_.hasr(a, "g")); // Return true
console.log(_.hasr(a, "h")); // Return true
console.log(_.hasr(a, "i")); // Return false
console.log(_.hasr(a, "j")); // Return false
答案 1 :(得分:0)
如果适合您,请尝试此操作:
_。有(o.c," d")