[英]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.