【问题标题】:Why does IndexOf return -1?为什么 IndexOf 返回 -1?
【发布时间】:2012-01-25 00:48:03
【问题描述】:

我正在学习Javascript,不明白为什么下面的indexOf返回-1:

var string = "The quick brown fox jumps over the lazy dog";

console.log (string.indexOf("good"));

【问题讨论】:

    标签: javascript indexof


    【解决方案1】:

    -1 表示“未找到匹配项”。

    它返回-1而不是“false”的原因是字符串开头的针会在位置0,这相当于Javascript中的false。因此,返回 -1 可确保您知道实际上没有匹配项。

    【讨论】:

    • 这就是我想要的。谢谢。
    • "它返回 -1 而不是 "false" 的原因是字符串开头的针在位置 0,相当于 Javascript 中的 false。所以返回 -1 可以确保你知道实际上没有比赛。”如果你使用像0 === false这样的严格比较,JS返回false(与undefinednull相同),所以似乎没有任何理由使用-1,因为你可以更直观地检查所有这些价值观。 JS arelady 有两个“空”值 - undefinednull,为什么不使用它们呢?
    【解决方案2】:

    -1 表示未找到匹配项。 “好”不在那句话里。这是documentedbehaviour

    indexOf() 方法返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回 -1

    【讨论】:

      【解决方案3】:

      因为数组是基于 0 的,所以返回 0 意味着从第一个字符开始匹配; 1、第二个字符,以此类推。这意味着任何 0 及以上的内容都是真实的或“找到的”响应。要将所有内容保持在整数类别中,-1 表示未找到匹配项。

      【讨论】:

        【解决方案4】:

        没有找到匹配项时 indexOf 返回 -1 的另一个原因。考虑下面的代码:

        if (~str.indexOf(pattern)){
          console.log('found')
        }else{
          console.log('not found')
        }
        

        因为 ~(-1) = 0 所以 indexOf 返回 -1 使得使用 ~ 编写 if...else 变得更容易。

        【讨论】:

          【解决方案5】:

          搜索永远不会找到它正在寻找的东西(“好”不在句子中),-1 是默认返回值。

          http://www.w3schools.com/jsref/jsref_indexof.asp

          【讨论】:

            【解决方案6】:

            相关问题;即使主题词存在于句子(语义上)或任何部分匹配的字母序列中,indexOf() 也会返回其第一个匹配字母的索引。例如

            const string = "The quick brown fox jumps over the lazy dog";
            console.log(string.length);
            // expected output: 43
            
            console.log (string.indexOf("fox"));
            // expected output: 16
            
            console.log (string.indexOf(" q"));
            // expected output: 3
            

            但如果部分字母序列与字符串数组的任何部分都不匹配,则该方法将返回-1,与“好”的情况相同;

            console.log (string.indexOf("foxy"));
            // expected output: -1
            
            console.log (string.indexOf("good"));
            // expected output: -1
            

            为了以防万一,可以使用 split() 方法将其转换为子字符串数组(这里是单词),用空格(标点符号)分割长字符串;

            const words = string.split(' ');
            console.log(words);
            // expected output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
            
            console.log(words.indexOf("fox"));
            // expected output: 3
            

            【讨论】:

              猜你喜欢
              • 2017-06-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-08-26
              相关资源
              最近更新 更多