1

最近我在JavaScript在寫邏輯和我寫了這樣的事情是String.contains在JavaScript中的標準功能?

var str="hello world"; 
 

 
if(str.contains("w")) 
 
    //do something 
 
else 
 
    //do anotherthing

我認爲這是工作的罰款,直到我跑的頁面在Chrome中。在Chrome中,我收到了一個錯誤contains is not a function

雖然我被修改邏輯

var str="hello world"; 
 
if(str.indexOf("w")!=-1) 
 
    //do something 
 
else 
 
    //do another thing

擺脫這contains不是標準的ECMAScript功能?我可以在Firefox中通過intellisense看到contains,但在Chrome中看不到。

雖然這些測試在不同的瀏覽器我在

String.subString/indexOf //not showing in chrome but works in Firefox

代替str.substring/indexOf作品鉻

是不是這些方法標準String對象的一部分控制檯注意到了嗎?

+3

'.includes'是該方法的標準名稱。 '.contains'是首選,但它打破了網站,因爲曾經流行的庫(Mootools)已經用不同的語義定義了字符串的「.contains」方法。 –

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – CodingIntrigue

回答

1

它被解釋爲here。 String.prototype.contains不是EsmaScript 5.1的一部分,它是當前版本。

+1

截至2015年6月,[* ECMAScript ed 6 *](http:// ecma-international .org/ecma-262/6.0/index.html)是目前的標準。 ;-) – RobG

0

.contains()不是標準字符串的部分物品

1

這是this問題重複。

爲方便起見,我會在這裏重新發布答案。

默認情況下,現在在Firefox和Chrome中支持此功能。如果您在此尋找最新答案,可以查看原因以及新方法名稱(即String.includes)here

嘗試:

yourString.includes( 'searchString的')