includes()函数的用法

在ES5,Array已经提供了indexOf用来查找某个元素的位置,如果不存在就返回-1,但是这个函数在判断数组是否包含某个元素时有两个小不足,第一个是它会返回-1和元素的位置来表示是否包含,在定位方面是没问题,就是不够语义化。另一个问题是不能判断是否有NaN的元素。

用法
str.includes(searchString[, position])
参数
searchString
要在此字符串中搜索的字符串。区分大小写。
position
可选。从当前字符串的哪个索引位置开始搜寻子字符串;默认值为0。

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

替代的方法

1. str.indexOf()

image

function fackIncludes(str,Field){
    if(str.indexOf(Field) != -1){
        return true
    }
    return false
}

image

2. str.search()

function fackIncludes(str,Field){
    if(str.search(Field) != -1){
        return true
    }
    return false
}

3. str.match()

function fackIncludes(str,Field){
    if(str.match(Field)){
        return true
    }
    return false
}

原文地址:https://www.cnblogs.com/ajaemp/p/11942056.html