取模运算符如何处理 Javascript 中的字符串

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));