[英]Javascript: Why does prefix operator work with modulus but not postfix operator?
[英]How does the modulus operator handle strings in Javascript
我知道模數一般是如何工作的,但我不清楚運算符如何處理字符串。 最近,我不得不編寫一個腳本來檢查名稱(字符串)是否包含偶數個字母。 這實際上有效,使用模數 2 並檢查結果是 1 還是 0:
function isNameEven(firstName) {
if (firstName % 2 === 0) {
return true;
}
else {
return false;
}
}
所以我假設字符串中的字母被計算在內?
結果總是NaN
const oneLetter = "a"; const twoLetters = "ab"; const threeLetters = "abc"; console.log(oneLetter % 2); console.log(twoLetters % 2); console.log(threeLetters % 2);
如果您向它傳遞一個無法隱式轉換為非NaN
的數字的字符串,則您的函數將不起作用。
function isNameEven(firstName) { if (firstName % 2 === 0) { return true; } else { return false; } } const oneLetter = "a"; const twoLetters = "ab"; const threeLetters = "abc"; console.log(isNameEven(oneLetter)); console.log(isNameEven(twoLetters)); console.log(isNameEven(threeLetters));
不過,您可以檢查字符串的長度屬性。
function isNameEven(firstName) { if (firstName.length % 2 === 0) { return true; } else { return false; } } const oneLetter = "a"; const twoLetters = "ab"; const threeLetters = "abc"; console.log(isNameEven(oneLetter)); console.log(isNameEven(twoLetters)); console.log(isNameEven(threeLetters));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.