TypeError模块中的语句不允许函数在没有第二个参数的情况下工作

时间:2017-03-07 19:14:39

标签: javascript typeerror prototype-programming

我想向String对象添加一个函数,该函数搜索所有字符串并返回我们想要查找的单词的索引。当我不使用startIndex参数时,它不应该抛出第二个错误,因为此语句typeof startIndex !== "undefined"允许此函数在没有startIndex的情况下工作。请指正,谢谢你的帮助。

String.prototype.allIndexOf = allIndexOfFunction;

function allIndexOfFunction(string, startIndex) {
    startIndex = startIndex || 0
    var indexArr = [];
    var sIndex = 0;
    var baseString = this.concat();
    if (typeof string === "string" && typeof startIndex === "number" && startIndex >= 0) {
        while(sIndex !== -1){
            sIndex = baseString.indexOf(string, startIndex);
            if(sIndex !== -1){
                indexArr.push(sIndex);
                startIndex = startIndex + sIndex +1;
            }
        }
    }
    try {
        if (typeof string !== "string") {
            throw "First parameter must be a string type";
        }
        else if (typeof startIndex !== "number" || typeof startIndex !== "undefined") {
            throw "Second parameter must be a number type";
        }
        else if (startIndex <= 0) {
            throw "Second parameter must be equal or bigger than 0";
        }
    } catch(err) {
        console.log(err);
    }

    return indexArr;
}
//TEST
var a = "Lorem ipsum dolor sit Buzz, consectetur Buzz elit. Quod vero voluptatibus Buzz error deserunt libero, Buzz incidunt Buzz facere! A!";
var test = a.allIndexOf("Buzz");
console.log("Searching indexes of \"Buzz\" word in string -> " + a);
console.log(test);

1 个答案:

答案 0 :(得分:0)

简单的问题。你的逻辑不太正确 - 你需要AND而不是OR:

将您的一行更改为:

else if (typeof startIndex !== "number" && typeof startIndex !== "undefined") {

此外,如果未定义startIndex,则默认为0,那么根本不需要第二次条件测试。

您可以在此处看到它按预期运行:

String.prototype.allIndexOf = allIndexOfFunction;

function allIndexOfFunction(string, startIndex) {
  startIndex = startIndex || 0
  var indexArr = [];
  var sIndex = 0;
  var baseString = this.concat();
  if (typeof string === "string" && typeof startIndex === "number" && startIndex >= 0) {
    while(sIndex !== -1){
      sIndex = baseString.indexOf(string, startIndex);
      if(sIndex !== -1){
        indexArr.push(sIndex);
        startIndex = startIndex + sIndex +1;
      }
    }
  }
  try {
    if (typeof string !== "string") {
      throw "First parameter must be a string type";
    }
    else if (typeof startIndex !== "number") {
      throw "Second parameter must be a number type";
    }
    else if (startIndex <= 0) {
      throw "Second parameter must be equal or bigger than 0";
    }
  } catch(err) {
    console.log(err);
  }

  return indexArr;
}
//TEST
var a = "Lorem ipsum dolor sit Buzz, consectetur Buzz elit. Quod vero voluptatibus Buzz error deserunt libero, Buzz incidunt Buzz facere! A!";
var test = a.allIndexOf("Buzz");
console.log("Searching indexes of \"Buzz\" word in string -> " + a);
console.log(test);