我似乎无法弄清楚match
在这个函数中的用途是什么?我尝试删除它,结果是
NaN 1,NaN 2和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));
下面的givin代码输出
没有柠檬,1个卷心菜和100个鸡蛋
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));