【问题标题】:How to check if value exists in an object in JavaScript如何在 JavaScript 中检查对象中是否存在值
【发布时间】:2017-02-13 17:57:16
【问题描述】:

我的 Angular 工厂服务中有一个函数可以获取一些数据。使用前如何检查对象内部是否存在某个值?

这是我一直在尝试的......

categories.fetch = function(app){
  if(!app.subject.name.length){
    return false;
  }
  var p = Restangular.all('v1/categories').getList({app.subject.name.toUpperCase()});
}

所以我只想在app.subject.name 调用之前检查app.subject.name 是否有价值...

谢谢

【问题讨论】:

    标签: javascript angularjs object


    【解决方案1】:

    您的代码将检索长度属性的值并尝试将其转换为布尔值以用于if/then 测试,但如果该值恰好是null,则会引发错误。

    此外,如果您的测试只是:app.subject.name,如果该值恰好是一个假值,您将得到一个误报,例如 0false,它们都是完全有效的值。

    对于字符串,最简单的测试是检查非空字符串和非空字符串。如果该值是由最终用户提供的,最好先在字符串上调用 .trim() 以删除可能无意添加的任何前导或尾随空格。

    var myObj = { 
      test : 0,
      testing : null
    }
    
    
    // This will fail with an error when the value is null
    /*
    if(myObj.testing.length){ 
      console.log("The testing property has a value."); 
    } else {
      console.log("The testing property doesn't have a value."); 
    }
    */
    
    // This will return a false positive when the value is falsy
    if(myObj.test){ 
      console.log("The test property has a value."); 
    } else {
      console.log("The test property doesn't have a value."); // <-- Incorretly reports this
    }
    
    // This explicit test will pass and fail correctly
    if(myObj.testing !== "" && myObj.testing !== null){ 
      console.log("The testing property has a value."); 
    } else {
      console.log("The testing property doesn't have a value."); 
    }

    另外,如果该值存在,请将您的代码放在ifs true 分支中,不要担心return false

    categories.fetch = function(app){
      if(app.subject.name !== "" && app.subject.name !== null) {
        var p = 
          Restangular.all('v1/categories').getList({app.subject.name.toUpperCase()});
      }
    

    【讨论】:

    • 但是长度属性为 0 是假的,所以 !object.length 只是检查它是否是 &gt;0 的简码
    • 如果name 根本不存在于app.subject 上,这也会抛出undefined TypeError
    • 当然会。只要您检查不存在的属性,就会发生这种情况。这就像说sdlfj = 894#$@$%$.[]{}{ 会抛出语法错误。
    • @Connum 由于属性有可能是null,所以根本不应该使用length,因为在这种情况下会抛出错误。
    【解决方案2】:

    hasOwnProperty() 方法返回一个布尔值,指示对象是否具有指定的属性。 MDN Docs

    例子

    var priceOfFood = {
        pizza: 14,
        burger 10
    }
    
    priceOfFood.hasOwnProperty('pizza') // true
    priceOfFood['pizza'] // 14
    priceOfFood.hasOwnProperty('chips') // false
    priceOfFood['chips'] // undefined
    

    【讨论】:

    • 这如何帮助检查属性是否具有值。问题不在于如何检查属性是否存在。
    • 这是一个类比的解释。我认为 OP 询问的不是检查值而是检查键。
    • OP 很清楚地说:“所以我只想检查 app.subject.name 中是否有值,然后再在 restanguar 调用中使用它”
    【解决方案3】:

    我知道这个问题不是关于 Lodash 的,但我设法用它做了很多检查,它完美地工作。在你的情况下,它会是这样的:

    categories.fetch = function(app){
      if (_.isEmpty(app.subject.name)) {
       return false;
      }
     var p = Restangular.all('v1/categories').getList({app.subject.name.toUpperCase()});
    }
    

    如果您认为应用对象中的键可能不可用,您可以这样做:

    categories.fetch = function(app){
      if (_.isEmpty(_.get(app, "subject.name"))) {
       return false;
      }
     var p = Restangular.all('v1/categories').getList({app.subject.name.toUpperCase()});
    }
    

    或者简单地说:

    categories.fetch = function(app){
      if (!_.get(app, "subject.name")) {
       return false;
      }
     var p = Restangular.all('v1/categories').getList({app.subject.name.toUpperCase()});
    }
    

    【讨论】:

    • 如果app.subject.name === ""怎么办?
    • 我看不出有什么问题,你能重新检查一下吗_.isEmpty(data.career.field) 应该返回 true。
    • 它确实返回 true,但如果值为空字符串,则不应该。
    • 啊对不起,我只是忘了从答案中删除否定,我已经更正了。
    • 所以问题出在原始答案上,否则_.isEmpty 正在按预期工作。
    【解决方案4】:

    就这么简单:

    if(!app.subject.name){
            return ;
        }
    

    【讨论】:

    • 正如我在其他几个答案中所指出的那样,如果该值是 0 或 false 之类的虚假值(这两个都是有效值),则会引发误报。
    • 它不会进入if 语句,因为输入值是一个字符串,因为if 语句中的表达式'0' 或'false' 是true
    • 这取决于测试的编写方式。 if("0" == true){} 产生false,而if("0"){} 产生true
    • 这就是为什么我让if 声明看起来像这样。
    • 我理解,但一般来说,当有一种技术可能模棱两可并可能导致错误,而另一种技术不是或不会时,建议使用后者。最好在调用.trim() 之后使用!== "" &amp;&amp; !== null 来测试字符串值是否存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2021-11-25
    • 2019-11-12
    相关资源
    最近更新 更多