我正在尝试创建一个JavaScript对象,它将对象作为输入,并返回对象中所有键的值。请帮助我查看我的代码,我没有得到我期望的结果。
var james = {
firstName: “James”,
lastName: “John”,
age: 40,
job: “programmer”,
married: false
};
function hasElObject(valObject, key) {
var i = valObject.length;
while (i--) {
if (valObject[i] === key) {
return valObject[i];
}
}
return ‘key not found’;
}
var objectEl = hasElObject (['congratulations', 'top', 8, 90], 5);
log (arrayEl);
var retValue = getValue(mary,email);
log (retValue);
答案 0 :(得分:1)
function hasElObject(valObject, key) {
for (var k in valObject) {
if (k == key)
return valObject[k];
}
return 'key not found';
}
var jobOfJames = hasElObject(james, "job");
console.log(jobOfJames);
答案 1 :(得分:1)
只需使用原生的基本JS:
function hasElObject(obj, key) {
return obj.hasOwnProperty(key) ? obj[key] : 'key not found';
}