es6 includes的用法----判斷一個字符串或數組是否包含一個指定的值


句法:

str.includes(searchString , [position]) 

searchString在此字符串內搜索的字符串。

position 可選的字符串中開始搜索的位置searchString(默認為0)。

返回值:

true:如果搜索字符串在給定字符串內的任何地方找到;返回true 

false:如果沒有找到返回false

描述:

此方法可讓您確定一個字符串是否包含另一個字符串。

includes()方法區分大小寫。例如,以下表達式返回false:

'Blue Whale'.includes('blue'); // returns false

運用:

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

填充工具:

此方法已添加到ECMAScript 2015規范中,可能尚未在所有JavaScript實現中提供。但是,您可以輕松地填充此方法:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }
    
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

不過填充工具是什么。最后一點沒有看懂

 

補充es5

es5中是用indexOf的命令來查找的,存在的返回的是索引值,不存在返回-1,但是NaN查找不出來,因為NaN!==NaN

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM