javascript函数,它接受两个输入:一个对象和一个键,并在该对象中返回该键的相应值

时间:2016-05-16 20:17:14

标签: javascript javascript-objects

我正在尝试创建一个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);

2 个答案:

答案 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';
}