【问题标题】:How to create a function that checks if a property exists in an object? [duplicate]如何创建一个检查对象中是否存在属性的函数? [复制]
【发布时间】:2021-06-26 06:40:17
【问题描述】:

我的任务是创建一个函数来检查对象中是否存在特定属性。我不明白为什么当数字对象中明显存在“b”时,第二个日志返回 false。如果有人可以向我解释解决方案会很高兴:)

const existInObject = (obj = {}, prop) => {
    for (const key in obj) {
      if(key === prop) {
        return true;
      } else {
        return false;
      }
    }
};

const numbers = { 
    a: 5,
    b: 4,
}

const result1 = existInObject(numbers, "a");
const result2 = existInObject(numbers, "b");

console.log(result1, result2); // true, false

【问题讨论】:

  • 内置的hasOwnProperty() 方法不是做你想做的吗?
  • 您在第一次迭代时返回,因此您只检查第一个属性是否匹配,而不是任何对象匹配。
  • const existInObject = (obj = {}, prop) => obj.hasOwnProperty(prop); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript function object properties conditional-statements


【解决方案1】:

它不起作用的原因是因为 Barmar 所说,“您在第一次迭代时返回,所以您只检查第一个属性是否匹配,而不是任何对象匹配”。您必须遍历所有键以查看是否匹配并返回结果。

const existInObject = (obj = {}, prop) => {
    var result = false;
    for (const key in obj) {
      if(key === prop) {
        result = true;
      }
    }
    return result
};

const numbers = { 
    a: 5,
    b: 4,
}

const result1 = existInObject(numbers, "a");
const result2 = existInObject(numbers, "b");
const result3 = existInObject(numbers, "c");

console.log(result1, result2, result3); // true, true, false

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多