好的,然后实现objContains函数:必须在嵌套对象内部搜索一对{key:value}特定的对象。 参数将接收对象和属性名称及其值。 如果它在对象的任何级别找到指示的值,它必须返回true,否则返回false。
Ex:
const user = {
id: 6,
email: 'homero@maxpower.com',
Personal info: {
name: 'Homer Simpson',
address: {
street: 'Avenue AlwaysLive',
number: 742,
neighborhood: 'Springfield',
state: 'Massachusetts'
}
}
}
返回true的大小写->; objContains(用户,“邻居”,“Springfield”);
返回false的大小写->; objContains(用户,“就业”,“核工厂雇员”);
提示:使用typeof确定属性的值是否是要应用递归的对象
这就是我试过的
var objContains = function (obj, prop, value) {
object var = prop.value
if (typeof prop.value === obj) {
var current = this.value;
objContains (object, prop, current)
} else if (this.prop === prop && prop.value === value) {
return true;
} else {
return false;
}
}
AssertionError: expected false to equal true
32 | }
33 | it ('It should return true if it finds the property and its correct value', fun
ction () {
> 34 | expect (objContains (user, "neighborhood", "Springfield")). to.equal (true);
35 | });
36 | it ('Should return false if the property is NOT found', function () {
37 | expect (objContains (user, "employment", "Employee at nuclear power plant")). to.equal (
false);
有几个问题:
>
typeofprop.value
检查具有文字名称value
的属性类型,无论prop
是什么。 您已经将prop
描述为对象属性的名称,因此尝试在其上查找value
是没有意义的。 您希望使用此问题答案中描述的语法查看obj
,而不是prop
。
如果在obj
上没有找到具有该值的属性,则应查看obj
上的其他属性,如果其中任何属性引用对象,则使用它们引用的对象(以及prop
和value
)调用函数,如果函数返回true
,则返回true
。 此问题的答案涵盖了对对象上属性的循环。
因此,解决方案的一般形式是:
obj
是否具有名称为prop
值且与value
值匹配的属性。 如果是,则返回true
.obj
的其他属性并检查其值的类型; 对于每个对象(typeof
是“object”
且值不是null
),用该属性值,prop
和value
再次调用函数。 如果返回true
,则返回true
。 如果没有,请继续循环。我有目的地只是给出一个去哪里的指示,而不是编写代码,因为这看起来像是一个我们应该帮助您而不是为您做的任务。