gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:38:41 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com