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

时间:2016-01-05 08:13:36

标签: javascript jquery

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

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

以上代码段为undefined返回something,但在控制台中也会记录为true。当条件满足时,为什么不返回present,我做错了什么?

3 个答案:

答案 0 :(得分:1)

  1. 我认为您实际上并不想将#PropertyField html解析为JSON,然后想要创建其jQuery对象。检查一下。
  2. 而不是jQuery(this)[0].properties.id,而只是执行this.id,这不是正确的语法。

答案 1 :(得分:1)

每种方法中提供的功能是匿名内部功能。因此,在每个()上下文之外不返回任何内容。要解决这个问题,你可以做类似的事情,

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

答案 2 :(得分: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");
相关问题