乘以数组javascript的某些元素

时间:2020-03-29 17:38:38

标签: javascript arrays loops

var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]

function validateCred(array) {
  let doubleArray =0
  for(i=array.length-2; i >= 0; i-=2) {
          doubleArray= array[i]*2
  }
  console.log(doubleArray);      
}

validateCred(valid1)  //prints 8 I want it to print entire loop

我正在尝试对luhn算法进行编码,这是从背面将第二个数字加倍的第一步,我希望我的结果等于doubleArray,但是当我尝试仅打印8张照片时

3 个答案:

答案 0 :(得分:0)

您可以参考下面的代码以获取所需的输出,即从背面开始将值加倍的数组。

  var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]

    function validateCred(array) {
       let doubleArray = [];
       for(i=array.length-2; i >= 0; i-=2) {
          doubleArray.push(array[i] * 2)
       }
       return(doubleArray);      
    }

    console.log(validateCred(valid1))

答案 1 :(得分:0)

因为只有步骤i-2,所以只有8张照片。另外,请参阅代码中有关反转数组的注释

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];

function validateCred(array) {
   let doubleArray = [];
   // we should move through all iterations that is why step i-=1
   for(let i = array.length-1; i >= 0; i -= 1) {
      // moving from the end of the array we will get reversed copy if using method push()
      // that is why changed to unshift()
      doubleArray.unshift((array.length - 1 - i) % 2 == 0 ? array[i] * 2 : array[i]);
      // array.length - 1 - i - using because we need to move from right in case length not odd
   }
   console.log(doubleArray);
}

// ES6+ syntax version version
function esValidateCred1(array) {
  const doubleArray = array.reverse().map((i, ind) => ind % 2 === 0 ? i*2 : i).reverse();
  console.log(doubleArray);;
}

validateCred(valid1);
esValidateCred1(valid1);

答案 2 :(得分:0)

最简单的方法是对数组使用 .map()方法

var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]

function validateCred(array) { 
  return array.map(item => item*2);      
}

console.log( validateCred(valid1) )  //prints array doubled elements