gpt4 book ai didi

javascript - 如何一次将一个元素多次添加到数组中

转载 作者:行者123 更新时间:2023-12-03 02:02:10 26 4
gpt4 key购买 nike

该函数应显示某个值对应的硬币数量;即:输入 56 应显示回 [25, 25, 5, 1]。

我遇到了麻烦:1)在数组中显示2个以上的同一枚硬币(我知道下面的数学函数没有正确使用)2) 从数组中删除所有 0

感谢您的帮助。

function getCoins(){
let coins = [25, 10, 5, 1];
amount = prompt ("Enter an amount to convert into coins");
coinAmount = "";


for (i = 0; i < coins.length; i++){
if (amount % coins[i] >= 0){
coinAmount += coins[i] * (Math.floor (amount/coins[i])) + ",";
amount = amount % coins[i];
console.log (coinAmount)
}
}
}

getCoins()

最佳答案

一种选择是push数组并使用join来显示它。

您可以将 coinAmount concat 到一个 new Array(NumberOfCouns) 并用硬币类型填充

function getCoins() {
let coins = [25, 10, 5, 1];
let amount = prompt("Enter an amount to convert into coins");
let coinAmount = [];


for (i = 0; i < coins.length; i++) {
if (Math.floor(amount / coins[i]) > 0) {

coinAmount = coinAmount.concat(new Array(Math.floor(amount / coins[i])).fill(coins[i]));
amount = amount - (Math.floor(amount / coins[i]) * coins[i]);
}
}

console.log(coinAmount.join())
}

getCoins();

关于javascript - 如何一次将一个元素多次添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49957971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com