jQuery检查值是否存在于对象数组中

3
我试图检查一个值是否存在于对象数组中。
function hasProperties(id){
    jQuery(JSON.parse(jQuery("#PropertiesField").html())).each(function () {
        if(id== jQuery(this)[0].properties.id) {
            console.log((id== jQuery(this)[0].properties.id));
            return "Present";
        }
    })
};
var something = hasProperties("someid");

上面的代码片段在something上返回了undefined,但是在控制台中也输出了true。为什么当条件满足时它没有返回present,我犯了什么错误?
3个回答

1
  1. 我认为你实际上并不想将 #PropertyField 的 html 解析为 JSON,然后再将其转换为 jQuery 对象。先对它进行检查。
  2. 不要使用 jQuery(this)[0].properties.id 这样的语法,直接使用 this.id 即可。

谢谢,现在我正在使用this.properties.id,但问题仍然存在。 它在控制台中记录“true”,但该值未被分配给变量。 - Vignesh Subramanian
@vignesh 只需要执行 this.id - void

1

在 each 方法中提供的函数是匿名内部函数。因此,在 each() 上下文之外不返回任何内容。为了解决这个问题,你可以这样做:

function getProperty(id){
var result;
    $('your element').each(function(){
        //If your condition is true
        result=expectedValue
    });
    return result;
}

0

我找到了问题所在,我的返回值是针对于.each()的。我在foreach函数外添加了一个返回值,现在它可以正常工作了。

function hasProperties(id){
var found =false;
    jQuery(JSON.parse(jQuery("#PropertiesField").html())).each(function () {
        if(id== jQuery(this)[0].properties.id) {
            console.log((id== jQuery(this)[0].properties.id));
            found= true;
            return;
        }
    })
return found;
};
var something = hasProperties("someid");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接