问题描述
我有两个数组。
VAR addFrom = [橙色,香蕉,西瓜,柠檬,桃花];
VAR AddTo就= [鸭梨,橘子,葡萄,橙色,蓝莓];
我想检查一下addFrom数组的第一个项目已经处于AddTo就数组。
如果在AddTo就数组不具有addFrom数组的第一个项目,我想推动此项目为AddTo就数组。
但是,如果addFrom数组中的第一项已经是AddTo就阵中,我想移动到第二项addFrom阵列中做同样的事情,直到我找到该项目在addFrom数组,它是不是AddTo就数组,然后将被推向AddTo就数组中为止。我想只有一个项目添加到AddTo就数组。
因此,我希望AddTo就数组是这样的:
VAR AddTo就= [鸭梨,橘子,葡萄,橙色,蓝莓,香蕉];
我怎样才能做到这一点在JavaScript中?
您可以使用的并停止迭代,如果一个项目是不是在 AddTo就
阵列。
VAR addFrom = [橙色,香蕉,西瓜,柠檬,桃花],\r
AddTo就= [鸭梨,橘子,葡萄,橙色,蓝莓];\r
\r
addFrom.some(函数(){\r
如果(!〜addTo.indexOf(一)){\r
addTo.push(一);\r
返回true;\r
}\r
});\r
\r
的document.write('< pre>'+ JSON.stringify(AddTo就,0,4)+'< / pre>');
\r
I have two arrays.
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
I would like to check if the first item in "addFrom" array is already in "addTo" array.
If the "addTo" array does not have the first item in "addFrom" array, I would like to push this item to "addTo" array.
However, if the first item in the "addFrom" array is already in the "addTo" array, I would like to move on to the second item in the "addFrom" array and do the same thing until I find the item in the "addFrom" array that is not in the "addTo" array, which will then be pushed to the "addTo" array. and I want to add only one item to the "addTo" array.
As a result, I want the "addTo" array to look like this:
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry", "banana"];
How can I do this in JavaScript?
You could use Array#some()
and stop the iteration if one item is not in the addTo
array.
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"],
addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
addFrom.some(function (a) {
if (!~addTo.indexOf(a)) {
addTo.push(a);
return true;
}
});
document.write('<pre> ' + JSON.stringify(addTo, 0, 4) + '</pre>');
这篇关于在JavaScript中从一个阵列中添加一个项目到另一个在比较两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!