[英]JS: Comparing Arrays and adding new items or removing items no longer in array
When I query my DB for items i generate an array say a list like 当我查询数据库中的项目时,会生成一个数组,例如
ArrayOne = [Apple, Banana, Orange, Banana]
//yes, an item can be there twice or more
then I duplicate it in a ArrayOne_Copy = ArrayOne
然后我将其复制到ArrayOne_Copy = ArrayOne
ok, then after an interval of 5 minutes I check again the DB and generate and replace the array ArrayOne
say now is like 好的,然后间隔5分钟后,我再次检查数据库并生成并替换数组ArrayOne
现在说的就像
ArrayOne = [Apple, Peach, Banana, Pineapple, Banana, Melon]
at this point I want to compare the ArrayOne_Copy
with the newly generated ArrayOne
and rebuild the list from the new list but without clearing the list and generating a new output, but i want to only add the new items or remove the one no longer in the list 在这一点上,我想将ArrayOne_Copy
与新生成的ArrayOne
进行比较,并从新列表重建列表,但不清除列表并生成新的输出,但是我只想添加新项或删除不再存在的项。名单
if I can "speak" code I would tell the script to: 如果我可以“讲”代码,我会告诉脚本:
Don't touch `Apple` because has not changed
Push 'Peach" between `Apple` and `Banana`
Push `Pineapple` between `Banana` and `Banana`
Remove `Orange`
Add `Melon`
so. 所以。 I'm kinda lost, and maybe the solution is very simple. 我有点迷路了,也许解决方法很简单。 Can you suggest the best practice? 您可以提出最佳做法吗?
You're not duplicating it, you're referencing it. 您不是在复制它,而是在引用它。
You will need to make a hard copy of the array which can be done using slice()
. 您需要制作一个数组的硬拷贝,可以使用slice()
。
var ArrayOne_Copy = ArrayOne.slice(0);
For example: 例如:
var ArrayOne = ['Apple', 'Banana', 'Orange', 'Banana'];
var ArrayOne_Copy = ArrayOne.slice(0);
ArrayOne.push('Melon');
console.log(ArrayOne);
console.log(ArrayOne_Copy);
http://jsfiddle.net/y7czyn3h/ http://jsfiddle.net/y7czyn3h/
http://davidwalsh.name/javascript-clone-array http://davidwalsh.name/javascript-clone-array
You can use this kind of function: 您可以使用这种功能:
Array.prototype.complete = function( arr ){
var result = new Array();
for( var a in arr )
result[ a ] = this[ a ] ? this[ a ] : arr[ a ];
return result;
}
Like this : 像这样 :
ArrayFull = ArrayOne_Copy.complete( ArrayOne );
Then ArrayFull
will be the array modified with . 然后ArrayFull
将是使用修改的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.