es6 includes的用法——判断一个字符串或数组是否包含一个指定的值

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

经典前端面试题每日更新,欢迎参与讨论,地址:https://github.com/daily-interview/fe-interview


更多angular1/2/4/5、ionic1/2/3、react、vue、微信小程序、nodejs等技术文章、视频教程和开源项目,请关注微信公众号——全栈弄潮儿

image

脑筋急转弯:

image

生活小窍门

image
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容