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

时间:2017-02-16 08:58:15

标签: javascript jquery

我似乎无法弄清楚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));

Code Reference

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

检查MDN,您会发现这是replace的回调函数的第一个参数。