Javascript 两个不同对的检查和排列

Javascript 两个不同对的检查和排列,javascript,Javascript,我想检查两个不同对的长度为5的数组,如果存在两对,将它们相加。我的思维过程是这样的: 对数组进行排序 如果数组中的第一个和第二个或第二个和第三个位置相同,请将它们的值添加到新数组中,然后从第一个数组中删除它们 重新开始,再次做同样的事情,但只添加下一对,如果它不等于第一对 如果第二个数组的长度为4,则对数组求和。如果长度不是4,则原始阵列不包含两个不同的对 下面是我想出的代码: /*temp is the array i test, it's just an array with length

我想检查两个不同对的长度为5的数组,如果存在两对,将它们相加。我的思维过程是这样的:

  • 对数组进行排序

  • 如果数组中的第一个和第二个或第二个和第三个位置相同,请将它们的值添加到新数组中,然后从第一个数组中删除它们

  • 重新开始,再次做同样的事情,但只添加下一对,如果它不等于第一对

  • 如果第二个数组的长度为4,则对数组求和。如果长度不是4,则原始阵列不包含两个不同的对

  • 下面是我想出的代码:

    /*temp is the array i test, it's just an array with length 5 
    filled with random integer values.*/
    var score = 0;
    var scoreArray = new Array();
    var flag = 0;
    /*My thought is, that's it's only necessary 
    to check the first two position to find a pair, 
    as the array only has a length of 5. */
    for(i = 0; i <= 1; i++){
        if(temp[i] == temp[i+1] && flag != temp[i]){
            flag = temp[i]
            scoreArray.push(temp[i], temp[i+1]);
            temp.splice(i, 2);
            i = -1;
        }
    }
    if(scoreArray.length == 4){
        for(i = 0; i < scoreArray.length; i++){
            score += scoreArray[i];
        }
    } 
    
    /*temp是我测试的数组,它只是一个长度为5的数组
    填充了随机整数值*/
    var得分=0;
    var scoreArray=新数组();
    var标志=0;
    /*我的想法是,那只是必要的
    要检查前两个位置以找到一对,
    因为数组的长度只有5*/
    
    对于(i=0;i我不能很好地理解这个问题,但我想你可以用 .map()或.filter()方法来获取所需的内容

    .map()循环遍历数组并返回新数组,因此可以使用此方法检查和修改每个元素:

    .filter()扫描数组,并返回通过扫描条件的新元素数组:

    例如,这是使用.map()方法实现的:


    希望这有助于

    您在完成检查时忘记了检查,因此在找到两对后,循环开始检查第三对,从剩余数组(当时有0或1个元素)中索引出来

    函数getScore(temp){
    临时排序();
    var scoreArray=[];
    var标志=0;
    对于(i=0;i parseInt(x));
    如果(arr.length==5&&!isNaN(arr[4]))
    res.innerText=getScore(arr);
    其他的
    res.innerText=“键入5个数字,数字之间有1-1个空格”;
    }
    test();


    您是否有一些示例和想要的结果?
    const temp = [1, 2, 3, 4, 5];
    
    console.log(temp);
    
    // loop through temp array to populate new array
    const updatedTemp = temp.map(element => {
        // if element have this value
      if (element === 1 || element === 2) {
          // do something to it
        return (element += 1);
      }
      // else just return the element
      return element;
    });
    // console.log the results
    console.log(updatedTemp);