javascript 如果您不知道javascript中每个数组的长度,如何比较两个不同长度的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8178086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to compare two arrays of different length if you dont know the length of each one in javascript?
提问by bentham
I am stuck in this. I got 2 arrays, I don't know the length of each one, they can be the same length or no, I don't know, but I need to create a new array with the numbers no common in just a (2, 10).
我被困在这。我有 2 个数组,我不知道每个数组的长度,它们可以是相同的长度,也可以不是,我不知道,但我需要创建一个新数组,其中的数字在 (2, 10)。
For this case:
对于这种情况:
var a = [2,4,10];
var b = [1,4];
var newArray = [];
if(a.length >= b.length ){
for(var i =0; i < a.length; i++){
for(var j =0; j < b.length; j++){
if(a[i] !=b [j]){
newArray.push(b);
}
}
}
}else{}
I don't know why my code never reach the first condition and I don't know what to do when b has more length than a.
我不知道为什么我的代码永远不会达到第一个条件,而且我不知道当 b 的长度大于 a 时该怎么办。
回答by BudgieInWA
It seems that you have a logic error in your code, if I am understanding your requirements correctly.
如果我正确理解您的要求,您的代码中似乎存在逻辑错误。
This code will put all elements that are in a
that are not in b
, into newArray
.
此代码会将所有a
不在 , 中的元素b
放入newArray
.
var a = [2, 4, 10];
var b = [1, 4];
var newArray = [];
for (var i = 0; i < a.length; i++) {
// we want to know if a[i] is found in b
var match = false; // we haven't found it yet
for (var j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
// we have found a[i] in b, so we can stop searching
match = true;
break;
}
// if we never find a[i] in b, the for loop will simply end,
// and match will remain false
}
// add a[i] to newArray only if we didn't find a match.
if (!match) {
newArray.push(a[i]);
}
}
To clarify, if
澄清一下,如果
a = [2, 4, 10];
b = [4, 3, 11, 12];
then newArray
will be [2,10]
然后newArray
将是[2,10]
回答by Selvakumar Ponnusamy
Try this
试试这个
var a = [2,4,10];
var b = [1,4];
var nonCommonArray = [];
for(var i=0;i<a.length;i++){
if(!eleContainsInArray(b,a[i])){
nonCommonArray.push(a[i]);
}
}
function eleContainsInArray(arr,element){
if(arr != null && arr.length >0){
for(var i=0;i<arr.length;i++){
if(arr[i] == element)
return true;
}
}
return false;
}