我的pangram javascript有什么问题?

时间:2019-11-19 04:01:02

标签: javascript

Pangram是一个获取输入并检查是否具有全部字母的函数,这是我使用ASCII代码的代码:

function pangram(x) {
    var a;

    for (var i = 97; i < 122; i++) {
        a = "&#" + i + ";";
        if (x.toLowerCase().includes(a) !== true) {
            break;
        }
    }
    if (i === 122) {
        return true
    } else {
        return false
    }
}

我认为问题是a = "&#" + i + ";" ;,但我不知道为什么会出现问题,它应该可以工作...

2 个答案:

答案 0 :(得分:2)

您已经接近答案了,但是代码存在一些问题,

  1. a =“&#” + i +“;”; ,这是做什么的?您可以使用String.fromCharCode(65);获取给定ASCII值的字符。更多信息:https://www.w3schools.com/jsref/jsref_fromcharcode.asp
  2. 如果未找到字符,则可以直接退出循环和函数,在该点之后没有点可以继续。

function pangram(x) {
    var a;

    for (var i = 97; i < 122; i++) {
        a = String.fromCharCode(i);;
        if (x.toLowerCase().includes(a) !== true) {
          // if atleast one letter was not found, we exit the function and the loop
          return false;
      }
    }

    // if it comes here, that means all the letters were found
    return true;
}

var isPangram = pangram("The quick brown fox jumps over the lazy dog");
console.log(isPangram);

答案 1 :(得分:1)

您需要使用charCodeAt()而不是手动手册。替换为以下条件:

if(x.toLowerCase().includes(String.fromCharCode(i))!==true)