Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

最近刷letcode碰到的小问题

indexOf

1
2
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:

1
2
3
4
'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

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

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

1
2
3
4
5
6
7
8
9
10
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;
};
}

评论