美文网首页
2021-10-10-🌦🌦 indexOf,includes,空

2021-10-10-🌦🌦 indexOf,includes,空

作者: 沐深 | 来源:发表于2021-10-10 22:03 被阅读0次

    最近刷letcode碰到的小问题

    indexOf

    let str = "string"
    str.indexOf("") // 0
    

    mdn解释
    The index of the first occurrence of searchValue, or -1 if not found.

    An empty string searchValue produces strange results. With no fromIndex value, or any fromIndex value lower than the string's length, the returned value is the same as the fromIndex value:

    'hello world'.indexOf('') // returns 0
    'hello world'.indexOf('', 0) // returns 0
    'hello world'.indexOf('', 3) // returns 3
    'hello world'.indexOf('', 8) // returns 8
    

    如果是空的,返回传入的序列,再往下需要查看js编译器源码了

    includes

    传入空字符串,返回true

    let str = "string"
    str.includes("") // true
    

    includes,polyfill,目测includes也是通过indexOf实现的

    if (!String.prototype.includes) {
      String.prototype.includes = function(search, start) {
         'use strict';
         if (search instanceof RegExp) {
          throw TypeError('first argument must not be a RegExp');
        }
        if (start === undefined) { start = 0; }
        return this.indexOf(search, start) !== -1;
      };
    }
    

    相关文章

      网友评论

          本文标题:2021-10-10-🌦🌦 indexOf,includes,空

          本文链接:https://www.haomeiwen.com/subject/kijkoltx.html