[英]How to check if value exists in an object in JavaScript
我的角度工厂服务中有一个函数来获取一些数据。 在使用对象之前,如何检查对象中是否存在某个值?
这是我一直在尝试的...
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属性的值,并尝试将其转换为Boolean以便进行if/then
测试,但是如果该值恰巧为null
,则会抛出错误。
另外,如果您的测试很简单: app.subject.name
,则如果该值恰好是伪造的值(例如0
或false
,它们都是完全有效的值,则您将得到假阳性。
对于字符串,最简单的测试是检查非空字符串和非空。 如果该值是由最终用户提供的,则最好先在字符串上调用.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
s 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()});
}
hasOwnProperty()方法返回一个布尔值,指示对象是否具有指定的属性。 MDN文件
例
var priceOfFood = {
pizza: 14,
burger 10
}
priceOfFood.hasOwnProperty('pizza') // true
priceOfFood['pizza'] // 14
priceOfFood.hasOwnProperty('chips') // false
priceOfFood['chips'] // undefined
我知道这个问题并不是关于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()});
}
就那么简单:
if(!app.subject.name){
return ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.