Jquery,检查数组中是否存在值 [英] Jquery, checking if a value exists in array or not

查看:40
本文介绍了Jquery,检查数组中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这个问题对于那些玩过 java script/jquery 的人来说会很容易.

I believe this question will be fairly easy for the ones who played around with java script / jquery.

var arr = new Array();

$.map(arr, function() {
 if (this.id == productID) {
   this.price = productPrice;
 }else {
  arr.push({id: productID, price: productPrice})
 }
}

我想上面的代码以非常简单的方式解释了我想要的东西.我想这个 $.map 会像这样工作,但不幸的是我无法得到结果.

I guess the code above explains what I want in really simple way. I would imagine this $.map would work like this but unfortunately I couldn't get results with this.

最简单、最优雅的方法是什么?我真的要遍历所有数组来查找键的值是否存在吗?

What is the most simple and elegant way to do this? Do I truly go through all array just to find if a key's value is there or not?

Jquery 有类似 isset($array['key']) 的东西吗?

Does Jquery has something like isset($array['key'])?

编辑

我尝试使用 inArray,但即使存在匹配项,它也会不断向数组添加对象.

I tried to use inArray but it keeps adding object to array even if there is a match.

if ( $.inArray(productID, arr) > -1) {
   var number = $.inArray(productID, arr);
   orderInfo[number].price = parseFloat(productPrice);
}else {
   orderInfo.push({id:productID, price:parseFloat(productPrice)});
}

推荐答案

如果你想使用 .map() 或者只是想知道它是如何工作的,你可以这样做:

If you want to do it using .map() or just want to know how it works you can do it like this:

var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

该函数分别处理每个元素.其他答案中提出的 .inArray() 可能是更有效的方法.

The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.

这篇关于Jquery,检查数组中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆