我似乎無法弄清楚什麼是match
在這個功能的目的配售的值?我嘗試將其刪除,結果是在參數javascript函數
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));
輸出
沒有檸檬,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));
爲什麼你減去的金額是多少?請參閱下面的代碼.. amount = Number(amount) - 1; –
@RanaGhosh我只是在讀博客。對不起,我不知道他在代碼中的含義。我包括參考。 – KiRa
的'minusOne'功能正在由'replace'作爲回調。見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – haim770