• 字符串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/

  • 相关阅读:
    编译安装mysql-5.6.36
    MYSQL数据库基础篇
    MYSQL数据库初学者必看
    Centos7下安装与卸载Jdk1.8
    Linux与Window之间的上传与下载
    MySQL主从搭建
    zabbix通过插件percona进行监控MySQL
    suse系统关闭防火墙
    编译安装zabbix3.0
    centos7安装tomcat
  • 原文地址:https://www.cnblogs.com/cathy1024/p/14085105.html
Copyright © 2020-2023  润新知