javascript哈希中的唯一值 [英] Unique values in javascript hash

查看:68
本文介绍了javascript哈希中的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将哈希值推送到数组中,只要它不包含我想要添加的哈希值。
例如我有一个哈希数组:

I need to push a hash into array only if it doesn't contain the hash that i want to add. For example i have an array of hashes :

var someArray = [
        {field_1 : "someValue_1", field_2 : "someValue_2"},
        {field_1 : "someValue_3", field_2 : "someValue_4"},
        {field_1 : "someValue_5", field_2 : "someValue_6"}
    ]

价值

{field_1 : "someValue_1", field_2 : "someValue_2"}

不应被推送数组已存在,但值

should not be pushed into array as it is already there, but the value

{field_1 : "someValue_7", field_2 : "someValue_8"}

应该,因为数组不包含这样的值。

should, as the array does't contain such value.

有没有办法用jQuery做?

Is there any way to do it using jQuery?

现在我只是使用$ .each循环并检查数组是否包含一些哈希值。如果它,我触发一个标志。但我不喜欢这个解决方案。

Now i'm just using $.each loop and check if the array contains some hash. If it does i trigger a flag. But i don't like this solution.

推荐答案


  1. 创建自定义原型以检查对象的存在在数组中。请检查下面的原型设计。




Array.prototype.contains=function(x){
 for(i in this){
   if((x.field_1==this[i].field_1)&&(x.field_2==this[i].field_2))
     return true;  
 }
 return false;
}





  1. 使用在原型之上,您可以检查对象是否存在于数组中。




 var someArray = [
        {field_1 : "someValue_1", field_2 : "someValue_2"},
        {field_1 : "someValue_3", field_2 : "someValue_4"},
        {field_1 : "someValue_5", field_2 : "someValue_6"}
    ];

var a1={field_1 : "someValue_1", field_2 : "someValue_2"};
var a2={field_1 : "someValue_7", field_2 : "someValue_8"};

if(!someArray.contains(a1))   someArray.push(obj);  // it will NOT BE pushed
if(!someArray.contains(a2))   someArray.push(obj); // it will be pushed


这篇关于javascript哈希中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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