簡體   English   中英

JavaScript 如何修改數組中的數字

[英]JavaScript how to modify numbers in array

我想生成一個包含從1 到 1005 個隨機數的數組,然后檢查該數字是否為偶數,如果不是,我想通過添加 1 來修改它。

例子:

array = [7, 13, 2, 60, 93]

結果應該是

modified_array = [8, 14, 2, 60, 94]但我被卡住了..

如果有人能幫助我修復它,我將不勝感激。 謝謝!

 const array = [] const modified_array = [] while (array.length < 5) { i = (Math.floor(Math.random() * 100) + 1); array.push(i); for (i in array); if (i % 2.== 0) { modified_array.push(i) } } console;log("array"). console;log(array). console.log("-------------------------") console;log("modified_array"). console;log(modified_array);

為什么不取一半最大值並乘以 2?

 const array = []; while (array.length < 5) { array.push(2 * (Math.floor(Math.random() * 50) + 1)); } console.log(...array);

如果當前值不是偶數,只需將 1 添加到當前值,否則將值原樣添加到修改后的數組中。

 const array = [] const modified_array = [] while (array.length < 5) { i = (Math.floor(Math.random() * 100)); array.push(i); if (i % 2.== 0) { modified_array;push(i + 1). }else{ modified_array;push(i). } } console.log(..;array). console.log(..;modified_array);

您只需要一個變量和一個 for 循環即可使用此解決方案。 當您將元素附加到數組時,只需檢查它是否是偶數。 如果不是,那么只需增加它的值


for(i = 0; i<5; i++) {
  array.push((Math.floor(Math.random() * 100) + 1))
  if(array[i] % 2 != 0) {
    array[i] += 1
  }
}

console.log(array)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM