将2个数组的元素相互比较并返回计数JavaScript [英] Compare 2 array's elements against each other and return count JavaScript

查看:74
本文介绍了将2个数组的元素相互比较并返回计数JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数组,我需要相互比较并返回相同的数量。

I have 2 arrays that I need to compare against each other and return the count of the same.

示例:将array1 [abcd]与array2进行比较[adce] 。返回为2,1,因为a和c处于相同位置且d处于错误位置。

Example: compare array1 [abcd] against array2 [adce]. Return would be 2,1 as both a and c are in same position and d is in the wrong position.

function () {
    var index = 0;
    for (index = 0; index < length; index++) {
        if (array1[index] == array2[index]) {
            count++
        } 
    }
    return count
}

我得到1的回报。我认为这是因为它们的长度相等,这就是为什么我得到1.所以我想我现在需要为循环添加另一个并让该循环去单独通过元素,但不知道如何做到这一点。我上面提到的可能完全错了,如果是的话,有人可以向我解释这个过程。

I'm getting a return of 1. I think that's because they equal in length that is why I'm getting a 1. So I'm thinking that I now need to put another for loop and have that loop go through the elements individually, but not sure how to do this. I could be completely wrong in what I have put above, if so, could someone explain the process to me please.

推荐答案

你获取 1 作为输出,因为 length 未在您的代码中定义

You get 1 as output because length is not defined in your code

var array1 = ['a','b','c','d'];
var array2 = ['a','d','c','e'];

var length = Math.min(array1.length,array2.length);
var countMatched = 0,countNotMatched = 0;

for(var index=0;index<length;index++)
{
  if(array1[index] == array2[index])
    countMatched++;
  else if(array2.indexOf(array1[index]) >= 0)
    countNotMatched++;
}
alert(countMatched );
alert(countNotMatched);

演示小提琴: http://jsfiddle.net/tCKE7/2/

这篇关于将2个数组的元素相互比较并返回计数JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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