2017-02-16 65 views
2

我似乎無法弄清楚什麼是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));

Code Reference

+0

爲什麼你減去的金額是多少?請參閱下面的代碼.. amount = Number(amount) - 1; –

+0

@RanaGhosh我只是在讀博客。對不起,我不知道他在代碼中的含義。我包括參考。 – KiRa

+1

的'minusOne'功能正在由'replace'作爲回調。見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – haim770

回答

4

String.prototype.replace()的函數有一個可選的功能參數here

這只是因爲它是該函數的內置行爲,如果您刪除了match它將用amount(在您的情況下)代替match。它只是沒有意義。

+0

感謝您的鏈接。 – KiRa

1

檢查MDN,你會發現,是的回調函數的第一個參數replace

+0

感謝您的鏈接。 – KiRa