js判断某数据是否包含某值

判断是否包含了某个数值或字符串

indexOf 没找到指定元素则返回 -1,找到则返回索引值
includes 返回布尔值
hasOwnProperty只用于对象,返回布尔值

字符串

includes、indexOf、startsWith、endsWith

startsWith参数二:搜索起点的位置,默认值为0。判断字符串是否以指定字符开头
endsWith参数二:设置字符串的长度,默认值为str.length。判断字符串是否以指定字符结尾

const str = 'Hello World'
str.includes('World', 5) // true

str.indexOf('World') //6

str.startsWith('Hell', 1)
str.endsWith('rld')

对象

hasOwnProperty、in、Reflect.has只检查对象包含这个key

var obj = {
    age: 18, name: undefined };
obj.hasOwnProperty('age'); // true

'name' in obj; // true
Reflect.has(obj, 'name') // true

Object.keys(obj).includes('name')

数组

数组中有多个相同的元素时,只匹配第一个;
includes数组对象不支持比较,请使用some

includes、indexOf、some、find、findIndex

const arr = [1, 2, 3,'san']
arr.includes(2)//true

arr.indexOf(2) //1 索引值
arr.indexOf(2) !== -1 //true

arr.some(item => item === 2) //true
arr.find(item => item === 2) !== undefined) //true
arr.findIndex(item => item === 2) !== -1   //true

最近更新

  1. TCP协议是安全的吗?

    2024-02-09 03:22:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-09 03:22:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-09 03:22:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-09 03:22:01       20 阅读

热门阅读

  1. VSCode 文件夹增加右键打开

    2024-02-09 03:22:01       30 阅读
  2. OLAP技术的发展及趋势简述

    2024-02-09 03:22:01       32 阅读
  3. MySQL视图和索引

    2024-02-09 03:22:01       32 阅读
  4. 作业2.5

    2024-02-09 03:22:01       27 阅读
  5. Lua语法

    Lua语法

    2024-02-09 03:22:01      29 阅读
  6. 【算法题】98. 验证二叉搜索树

    2024-02-09 03:22:01       31 阅读
  7. 开源软件的影响力

    2024-02-09 03:22:01       36 阅读
  8. 开源软件对技术以及行业发展的影响

    2024-02-09 03:22:01       32 阅读