jQuery的,检查是否存在数组或者不是一个价值 [英] Jquery, checking if a value exists in array or not

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

问题描述

我相信这个问题将是相当容易的谁与Java脚本/ jQuery的周围起的人。

  VAR ARR =新的Array();$ .MAP(ARR,函数(){
 如果(this.id ==的productID){
   this.price = productSku,则;
 }其他{
  arr.push({ID列:ProductId,价格:productSku,则})
 }
}

我猜code以上解释什么,我想非常简单的方法。我可以想象这$ .MAP将这样的工作但遗憾的是我不能这样得到的结果。

什么是最简单,最优雅的方式来做到这一点?我才真正通过所有数组只找到,如果键的值是有或没有?

请问jQuery有类似使用isset($数组['关键'])

修改

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

 如果($ .inArray(的productID,ARR)-1个){
   变种数= $ .inArray(的productID,ARR);
   OrderInfo的[数字]。价格= parseFloat(productSku,则);
}其他{
   orderInfo.push({ID列:ProductId,价格:parseFloat(productSku,则)});
}


解决方案

如果您想用做 .MAP()或只是想知道它是如何运作的,你能做到这一点是这样的:

  VAR添加= FALSE;
$ .MAP(ARR,功能(elementOfArray,indexInArray){
 如果(elementOfArray.id ==的productID){
   elementOfArray.price = productSku,则;
   添加= TRUE;
 }
}
如果(!添加){
  arr.push({ID列:ProductId,价格:productSku,则})
}

功能分别处理每个元素。在 .inArray()其他答案建议很可能是做更有效的方式。

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})
 }
}

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?

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

EDIT

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

解决方案

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})
}

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天全站免登陆