どのようにJavaScriptで剰余演算子ハンドル文字列はありません

I:

私は、弾性率は、一般的にどのように動作するかを知っているが、それは私にどのようにオペレータハンドル文字列は明らかではありません。最近、私は名前(文字列)文字の偶数が含まれている場合にチェックするスクリプトを記述する必要がありました。これは実際にモジュラス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));

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=30485&siteId=1