2016-09-23 97 views
0

我試圖讓另一個值爲什麼'abc'.indexOf([])=== 0?

let index = 'any string'.indexOf([]); 
console.log(index); // 0 

爲什麼索引值0的字符串索引?

+0

每個字符串包含空字符串。就像一個空集是每個集的一個子集。 –

回答

2

String.prototype.indexOf轉換的任何對象,給定爲一個搜索模式,以一個字符串。的[]

字符串表示是''(空字符串)。
如果你申請indexOf('')爲任何字符串,它會返回0

console.log([].toString()); 
 

 
console.log('qwerty'.indexOf([])); // this one gives the same result 
 
console.log('qwerty'.indexOf('')); // as this one 
 

 
console.log(['a', 1].toString()); 
 

 
console.log('gfdsa,12345'.indexOf(['a', 1])); // these two give 
 
console.log('gfdsa,12345'.indexOf('a,1')); // the same result as well