jquery检查对象数组中存在的值

jquery check value present in an object array

本文关键字:存在 数组 检查 对象 jquery      更新时间:2023-09-26

我正在尝试检查对象的数组中是否存在值

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,我犯了什么错误?

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

function getProperty(id){
var result;
    $('your element').each(function(){
        //If your condition is true
        result=expectedValue
    });
    return result;
}
  1. 我不认为您真的想将#PropertyFieldhtml解析为JSON,然后制作它的jQuery对象。检查一下
  2. 不做jQuery(this)[0].properties.id,只做this.id,这不是一个正确的语法

我发现了问题,返回的是.each()。我在foreach函数外添加了一个return,它现在可以工作了

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");