我想比较每个索引的数组与另一个数组的每个索引

时间:2014-07-08 06:09:45

标签: javascript dom

这里我在这段代码中定义了2个数组temp_Array和storage_Array。当我输入数据时,它被写入临时。我想比较每个temp的索引与每个存储索引,以便我将存储作为一个唯一的数组。因此,当且仅当它不存在时,它才会将值从temp推送到存储。

<!doctype html>
<html>
<head>
<title>jQuery UI Dialog - Default functionality</title>
<style>
body {
font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
               font-size: 62.5%;
}
</style>
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery-1.11.1.js"></script>
<script src="jquery-ui.js"></script>
<script>

$(document).ready(function() { 
$('path') .dblclick(function(){
$(function() {
$( "#dialog" ).dialog();
});
});
$('.cat') .click(function(){
$(function(){
$('#dialog').dialog('close');
});
});
});
</script>
</head>
<body>
<svg width="80" height="32">
<path d="M10 15 l15 0 l2.5 -5 l5 10 l5 -10 l5 10 l5 -10 l5 10 l2.5 -5 l15 0" stroke="black" stroke-width="2px" stroke-linejoin="bevel" fill="none"></path>
</svg>
<div id="dialog" title="Basic dialog" style="display:none">
<form>
Component-ID: <input type="text" name="id1" id ='id1'><br>
Componentval: <input type="text" name="val1" id ='val1'><br>
<input class="cat" type="button" value="Submit" onclick="loop();">
<script>
var storage_Array =[];
var temp_Array =[];
function writedata(){

//console.log(document.getElementById("id1"));
temp_Array.push({'id':  document.getElementById("id1").value, 'val': document.getElementById("val1").value});
//console.log(storage_Array);
}
for(var i=0;i < 5; i++){
writedata();
}
console.log(temp_Array);
console.log(storage_Array);
}
</script>
</form>
</div>
</body>

1 个答案:

答案 0 :(得分:0)

要检查数组中是否已存在某些内容,通常可以使用本机javascript方法indexOf()或jQuery&#39; s inArray()等实用程序方法。

但是,因为您的数组包含对象,所以您需要做更多的工作。正如this question中所讨论的,javascript没有提供一种通用方法来根据内容确定两个对象是否相等。

有几种解决方案。您可以编写一个函数isEqual(objectA, objectB)来检查idval的值。每次插入新对象时,都需要遍历数组并使用此函数来确保对象不存在。

另一种方法是更改​​存储结构。它取决于数据是什么,但有时可能适合在对象内按ID分组。存储格式类似于:

{
  id_1: [value_1, value_2],
  id_2: [value_3]
}

然后您可以通过以下方式有条件地添加到存储中:

newId = document.getElementById("id1").value;
newVal = document.getElementById("val1").value;
if(!(newId in storage)) {
    storage[newId] = [newVal];
} else if(-1 === $.inArray(newVal, storage[newId])) {
    storage[newId].push(newVal);
}
相关问题