[英]multiplying certain elements of an array javascript
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 個
您可以參考下面的代碼來獲得所需的輸出,即從后面開始具有加倍值的數組。
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))
你只有 8 張照片,因為你有 step i-2
。 另外,請參閱代碼中有關反轉數組的注釋
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);
最簡單的方法是對數組使用.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.