indexOf empty string is zero. why?

家住魔仙堡 提交于 2019-12-14 04:23:35

问题


why this is happening in javascript?

'abc'.indexOf('a');        //0
'abc'.indexOf('');         //0

while in the other falsy values, the value is -1:

'abc'.indexOf();           //-1
'abc'.indexOf(false);      //-1
'abc'.indexOf(undefined);  //-1

i have seen also those questions:
Q1 didnt understand the answer in depth.
Q2 in java and not javascript.


回答1:


The answer, fundamentally, is: Because that's how the function is specified to behave. And it makes sense, from a certain perspective.

The main bit related to returning 0 when you search for an empty string is this:

Return the smallest possible integer k not smaller than start such that k + searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the code unit at index k + j within S is the same as the code unit at index j within searchStr; but if there is no such integer k, return the value -1.

Since the length of the search string is 0, both halves of that "and" are satisfied by k = 0: k + searchLen is not greater than the length of the string, and for all nonnegative integers less than the search length (there are zero), the code points match.

Or roughly speaking, in code:

function indexOf(searchString, position = 0) {
    let s = String(this);
    let searchStr = String(searchString);
    let len = s.length;
    let start = Math.min(Math.max(position, 0), len);
    let searchLen = searchStr.length;
    let k = 0;
    while (k + searchLen <= len) {
        if (s.substring(k, k + searchLen) === searchStr) {
            break;
        }
        ++k;
    }
    const found = k + searchLen <= len;
    return found ? k : -1;
}

Since k + searchLen (0) is <= len (0), k (0)` is returned.

Live Example:

function indexOf(searchString, position = 0) {
    let s = String(this);
    let searchStr = String(searchString);
    let len = s.length;
    let start = Math.min(Math.max(position, 0), len);
    let searchLen = searchStr.length;
    let k = 0;
    while (k + searchLen <= len) {
        if (s.substring(k, k + searchLen) === searchStr) {
            break;
        }
        ++k;
    }
    const found = k + searchLen <= len;
    return found ? k : -1;
}

console.log(indexOf.call("abcd", ""));

Another way to look at it is this answer related to Java...or to life in general.


Re your question passing in non-strings: One of the first steps is:

Let searchStr be ? ToString(searchString).

...which is let searchStr = String(searchString); in my rough code above. That means false becomes "false" and undefined becomes "undefined". "abc" doesn't contain either "false" or "undefined".



来源:https://stackoverflow.com/questions/52624181/indexof-empty-string-is-zero-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!