gpt4 book ai didi

javascript - 在函数中传递对象

转载 作者:行者123 更新时间:2023-12-04 07:12:49 26 4
gpt4 key购买 nike

我正在做一个 freecodecamp 挑战,我被要求完成一个函数,如果传递的对象包含所有四个名称,则返回 true:'Alan' 'Jeff' 'Ryan' 'Sarah'。
之前定义了一个对象,其中包含数据:

let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
等等。
函数是这样开始的
function isEveryoneHere(userObj) {}
我把这个写成我完成的函数,我可以在其中返回所有 4 个名字:
for (const property in userObj) {
if (userObj) {
return userObj.hasOwnProperty(property)
}
但我仍然被告知我没有达到挑战的标准。任何指示或建议提示?

edit: Error Message The users object should not be accessed directly

Passed The users object should only contain the keys Alan, Jeff,Sarah, and Ryan

Passed The function isEveryoneHere should return true if Alan, Jeff,Sarah, and Ryan are properties on the object passed to it.

The function isEveryoneHere should return false if Alan is not aproperty on the object passed to it.

The function isEveryoneHere should return false if Jeff is not aproperty on the object passed to it.

The function isEveryoneHere should return false if Sarah is not aproperty on the object passed to it.

The function isEveryoneHere should return false if Ryan is not aproperty on the object passed to it

最佳答案

我可能会做类似的事情

let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
}

function check(userObj) {
return ['Alan', 'Jeff', 'Ryan', 'Sarah'].every(user => userObj.hasOwnProperty(user));
}

function check2(userObj) {
return ['Alan', 'Jeff', 'Ryan', 'Sarah'].every(user => Object.keys(userObj).includes(user));
}

console.log('check: ' + check({ Jeff: 1, Alan: 2, Ryan: 3, Sarah: 4 }));
console.log('check2: ' + check2({ Jeff: 1, Alan: 2, Ryan: 3, Sarah: 4 }));
console.log('Should fail (check): ' + check(users));
console.log('Should fail (check2): ' + check2(users));

两种变体都应满足所有标准——除了不应该直接访问对象的标准。我不确定他们的意思,但第二个将键转换为数组,所以也许这就是他们正在寻找的,即使它效率低下。

关于javascript - 在函数中传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68968967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com