比较数组Javascript中索引元素中的数字

时间:2018-10-11 16:53:57

标签: javascript arrays indexing compare element

给出了一个像['8:2', '3:2', …]这样的数组,我想比较数组每个元素中的每个数字。因此Index[0]将8与3进行比较,依此类推。 如果A等于B,则它应获得某个值;如果A小于B,则应获得另一个值。 我只是不知道如何在索引元素中比较这些数字,以便将新值存储到第二个数组中。

我尝试过这个:

function check(games) {
var newArr = [];
var value;
//var newArr = [];
  for (var j=0; j<=games.length; j++){
    if (games[j].a === games[j].b ) {
      value = 0;
      newArr.push(value);
      //alert(newArr);
      //return value;
    }
    else if(games[j].a > games[j].b ) {
      value = 2;
      newArr.push(value);
      //alert(newArr);
    }
    alert(newArr.join(''));
  }

}

check(['3:3', '2:1']);

比起我用for… in尝试过,但它也不起作用… (我的代码示例已缩短)

function check(games) {
var arr = games;
var arrNew = [];
  for (var prop in games) {
    if (a === b) {
    var value = 0;
    arrNew.push(value);
    alert(arrNew.join(''));
    }
  }
}

 check(['3:3', '2:1']);

如何比较索引中存储的元素? Like Index [0] =(“ 3:3')-如何比较a和b,以便可以迭代到下一个索引?

谢谢

1 个答案:

答案 0 :(得分:3)

const list = ['8:2', '3:2'];
list.forEach((e) => {
  const [a, b] = e.split(':').map(Number);
  if (a > b) {
    // a is greater than b
  } else if (a < b) {
    // b is greater than a
  } else {
    // a and b are equal
  }
});