jquery,检查数组中是否存在值

我相信这个问题对于那些使用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会像这样工作,但不幸的是我无法得到这个结果。

什么是最简单和优雅的方式来做到这一点? 我是否真的通过所有数组来查找密钥的值是否存在?

Jquery是否有像isset($array['key'])

编辑

我试图使用inArray,但是它保持添加对象数组,即使有一个匹配。

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

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

 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()可能是更有效的方法。

http://api.jquery.com/jQuery.inArray/

 if ($.inArray('example', myArray) != -1) { // found it } 

jQuery有inArray函数:

http://api.jquery.com/jQuery.inArray/

  if ($.inArray('yourElement', yourArray) > -1) { //yourElement in yourArray //code here } 

参考: JQuery数组

$ .inArray()方法类似于JavaScript的本地.indexOf()方法,因为它在找不到匹配项时返回-1。 如果数组中的第一个元素匹配值,$ .inArray()返回0。

试试jQuery.inArray()

这里是一个jsfiddle链接使用相同的代码: http : //jsfiddle.net/yrshaikh/SUKn2/

$ .inArray()方法类似于JavaScript的本地.indexOf()方法,因为它在找不到匹配项时返回-1。 如果数组中的第一个元素匹配值,$ .inArray()返回0

示例代码

 <html> <head> <style> div { color:blue; } span { color:red; } </style> <script src="jquery-latest.js"></script> </head> <body> <div>"John" found at <span></span></div> <div>4 found at <span></span></div> <div>"Karl" not found, so <span></span></div> <div> "Pete" is in the array, but not at or after index 2, so <span></span> </div> <script> var arr = [ 4, "Pete", 8, "John" ]; var $spans = $("span"); $spans.eq(0).text(jQuery.inArray("John", arr)); $spans.eq(1).text(jQuery.inArray(4, arr)); $spans.eq(2).text(jQuery.inArray("Karl", arr)); $spans.eq(3).text(jQuery.inArray("Pete", arr, 2)); </script> </body> </html> 

输出:

 “约翰”3号find
 4在0find
 “卡尔”未find,所以-1
 “Pete”在数组中,但不在索引2或索引2之后,因此为-1