gpt4 book ai didi

javascript - 在 javascript 函数的参数中放置一个值

转载 作者:行者123 更新时间:2023-11-29 16:45:09 25 4
gpt4 key购买 nike

我似乎无法弄清楚这个函数中 match 的目的是什么?。我尝试删除它,结果是

NaN 1, NaN 2, and NaN 101

var stock = "1 lemon, 2 cabbages, and 101 eggs";
function minusOne(amount, unit) {
amount = Number(amount) - 1;
if (amount == 1) // only one left, remove the 's'
unit = unit.slice(0, unit.length - 1);
else if (amount == 0)
amount = "no";
return amount + " " + unit;
}
console.log(stock.replace(/(\d+) (\w+)/g, minusOne));


下面给出的代码的输出

no lemon, 1 cabbage, and 100 eggs

var stock = "1 lemon, 2 cabbages, and 101 eggs";

function minusOne(match, amount, unit) {
amount = Number(amount) - 1;
if (amount == 1) // only one left, remove the 's'
unit = unit.slice(0, unit.length - 1);
else if (amount == 0)
amount = "no";
return amount + " " + unit;
}
console.log(stock.replace(/(\d+) (\w+)/g, minusOne));

<强> Code Reference

最佳答案

String.prototype.replace() 函数采用可选函数参数 here .

这只是因为它是函数的内置行为,如果您删除 match ,它会将 match 替换为 amount (在你的情况下)。这根本没有意义。

关于javascript - 在 javascript 函数的参数中放置一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269143/

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