字符串includes()和数组includes()

字符串includes()和数组includes()

 

 

字符串的includes()方法

参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/includes

String.prototype.includes() 

用于判断一个字符串是否包含在另一个字符串中,根据情况返回true或false

该方法已被加入ECMAScript6标准中

 

【语法】

str.includes(searchString[, position])

 

【参数】

- searchString 要在此字符串中搜索的字符串

- position 可选

从当前字符串的哪个索引位置开始搜寻子字符串,默认值0

如果为负值,则等同于为0

 

【返回值】

如果当前字符串包含被搜寻的字符串返回true, 否则返回false

 

【示例】

复制代码
var str = 'To be, or not to be, that is the question.'
str.includes('To be');
// true
str.includes('question');
// true
str.includes('nonexistent');
// false
str.includes('To be', 1);
// false
str.includes('TO BE');
// false
复制代码

 

【浏览器兼容性】

 

 不支持IE!!!

 

 

数组的includes()方法

文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

 

Array.prototype.includes()

includes函数用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回true, 否则返回false

Demo

复制代码
const array1 = [1, 2, 3];

console.log(array1.includes(2));  // true


const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat')); // true

console.log(pest.includes('at')); // false
复制代码

 

【语法】

arr.includes(valueToFind[, fromIndex]);

 

【参数】

- valueToFind

需要查找的元素值

- fromIndex 可选

从fromIndex索引处开始查找,如果为负值,则从arr.length + fromIndex的位置开始查找

 

【返回值】Boolean

 

更多示例

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3, 4, 5, 6, 7, 8].includes(2, 1); // true
[1, 2, 3, 4, 5, 6, 7, 8].includes(2, 2); // false

[1, 2, NaN].includes(NaN);

 

如果fromIndex大于等于数组长度,则返回false,且该数组不会被搜索

var arr = ['a', 'b', 'c'];

arr.includes('c', 3); // false
arr.includes('c', 100); // false

如果fromIndex为负值,计算出的索引将作为开始搜索searchElement的位置。

如果计算出的索引小于0,则整个数组都会被搜索

示例

[1, 2, 3, 4, 5].includes(1, -1); // false
[1, 2, 3, 4, 5].includes(5, -1); // true
[1, 2, 3, 4, 5].includes(4, -1); // false
[1, 2, 3, 4, 5].includes(4, -2); // true
[1, 2, 3, 4, 5].includes(5, -2); // true

 

作为通用方法的includes()

includes()方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象(比如类数组对象)。示例:

(function(){
    console.log([].includes.call(arguments, 'a')); // true
    console.log([].includes.call(arguments, 'd')); // false
})('a', 'b', 'c')

 

【浏览器兼容性】

 

 不支持IE !!!

 

 

【更多扩展】

ES7文档(英文): https://www.ecma-international.org/ecma-262/7.0/

 

posted on   独自去流浪  阅读(2330)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示