javascript - 如何检查 JavaScript 中对象中是否存在值

标签 javascript angularjs object

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

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

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

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

谢谢

最佳答案

您的代码将检索 length 属性的值并尝试将其转换为 bool 值以用于 if/then 测试,但如果该值恰好是

此外,如果您的测试很简单: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."); 
}

此外,如果该值存在,请将您的代码放在 if 的 true 分支中,不要担心返回 false

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

关于javascript - 如何检查 JavaScript 中对象中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42210451/

相关文章:

javascript - 触摸事件不适用于多个模态框

javascript - 使用 Bootstrap 和 jQuery 无法很好地呈现多个分页器

javascript - 如果 Span Class Text = 1,如何将 boxShadow 添加到 Span Class?

angularjs - 如何在 AngularJS 中从我的应用程序配置中设置 $httpProvider 默认 header ?

javascript - Typescript-将属性设置为对象

javascript - 什么样的对象在控制台中显示为 [object Text]?

javascript - 如何在 jQuery 中隐藏适当的面板,其中有 2 个具有相同的类?

javascript - 在依赖于 ANGULAR.JS 的下拉列表中选择默认选项

c++ - C++ 中类原型(prototype)的问题

javascript - 如何添加具有数据属性的类?