简体   繁体   English

比较 2 个在 Javascript 中不起作用的数组的值

[英]Comparing between values of 2 arrays not working in Javascript

im trying to compare between two arrays, whether they have same value at same place, same values at different places or not the same at all.我试图在两个数组之间进行比较,无论它们在同一位置具有相同的值,在不同位置具有相同的值还是根本不相同。 after comparing I want to enter a char to a third array to indicate the result.比较后我想输入一个字符到第三个数组来指示结果。 my code doesnt work for some reason... its not comparing correctly.我的代码由于某种原因不起作用......它没有正确比较。 what am i doing wrong?我究竟做错了什么?

var numInput = [1,2,3,4];
var numArr = [2,5,3,6];
var isBp;
var i,j;
  for ( i = 0; i < 4; i++)
   {
     if (numInput[i] == numArr[i])
     {  isBP[i] = "X"; }
     else
     {
       for ( j = 0; j<4; j++)
       {
         if (numInput[i] == numArr[j])
          {isBP[i] = "O";}
         else
          { isBP[i] = "-"; }
       }

     }

     }

the result should be:结果应该是:

isBP = [O,-,X,-]

This is a fairly simple array map operation.这是一个相当简单的数组映射操作。 If I understand correctly you want an X when they match and an O when they don't and that doesn't exist at all and - when it exists but at different location如果我理解正确,当它们匹配时需要一个X当它们不匹配时需要一个O并且根本不存在-当它存在但在不同的位置时

 var numInput = [1,2,3,4]; var numArr = [2,5,6,4]; var isBP = numInput.map((n,i) => ((n === numArr[i] ? 'X' : numArr.includes(n) ? '-': 'O'))) console.log(isBP)

It looks like you'd like to output:看起来你想输出:

  • X if the numbers at the same indexes are equal X 如果相同索引处的数字相等
    • if they are not equal at the same indexes, but the number is found elsewhere如果它们在相同的索引处不相等,但该数字在别处找到
  • O if the number from the first array doesn't exist in the second at all O 如果第一个数组中的数字在第二个数组中根本不存在

if so:如果是这样的话:

var a1 = [1, 2, 3];
var a2 = [1, 3, 4];

var result = a1.map((n, i) => {
  var match = a2.indexOf(n);
  if (match === i) {
    return "X"
  } else if (match > -1) {
    return "O";
  } else {
    return "-";
  }
});

console.log(result); // prints [ 'X', '-', 'O' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM