美文网首页
include 与 indexof

include 与 indexof

作者: Max_Law | 来源:发表于2023-12-24 09:26 被阅读0次

简介

includes()indexOf() 是 JavaScript 中用于在数组或字符串中查找特定元素的方法。以下是它们的用法和区别:

includes()

  • 用法:

    array.includes(searchElement[, fromIndex])
    string.includes(searchString[, position])
    
    • 返回值:布尔值。如果在数组或字符串中找到了指定的元素或子字符串,返回 true,否则返回 false

    • 参数:

      • searchElement(数组)或 searchString(字符串):要查找的元素或子字符串。
      • fromIndex(可选,数组):开始搜索的索引位置,默认为 0。
      • position(可选,字符串):开始搜索的字符位置,默认为 0。

indexOf()

  • 用法:

    array.indexOf(searchElement[, fromIndex])
    string.indexOf(searchValue[, fromIndex])
    
    // 快捷判断方法
    if(!~array.indexOf(0)){
      // 不存在时的操作
    }
    
  • 返回值:整数。如果在数组或字符串中找到了指定的元素或子字符串,返回它第一次出现的索引位置,否则返回 -1

  • 参数:

    • searchElement(数组)或 searchValue(字符串):要查找的元素或子字符串。
    • fromIndex(可选,数组和字符串):开始搜索的索引位置,默认为 0。

区别

  • includes() 方法返回的是布尔值,表示是否找到指定的元素或子字符串,而 indexOf() 方法返回的是找到的元素或子字符串的索引位置,或者 -1 表示未找到。
  • indexOf() 在查找 NaN 时可能会出现问题,因为 NaN 不等于自身,所以使用 array.indexOf(NaN) 可能无法正确判断数组中是否存在 NaN。而 includes() 方法可以正确判断数组中是否包含 NaN

以下是一些示例:

let arr = [1, 2, 3, NaN, 5];
let str = 'Hello, world!';

console.log(arr.includes(3)); // true
console.log(arr.includes(NaN)); // true
console.log(str.includes('world')); // true

console.log(arr.indexOf(3)); // 2
console.log(arr.indexOf(NaN)); // -1 (这里无法正确判断)
console.log(str.indexOf('world')); // 7

对于稀疏数组处理

indexOf()includes() 方法在处理稀疏数组时的行为是相同的。

稀疏数组是指数组中包含未定义或空的元素,即不是一个连续的元素序列。例如:

// 稀疏数组,索引 0、1、3 上的元素未定义
let sparseArray = [, , 3, , 5];

当在稀疏数组中使用 indexOf()includes() 查找元素时:

  • 如果查找的元素存在于数组中(即使是在未定义的索引位置),这两个方法都会返回该元素的索引。
  • 如果查找的元素不存在于数组中,这两个方法都会返回 -1(对于 indexOf())或 false(对于 includes())。

以下是一个示例:

let sparseArray = [, , 3, , 5];

console.log(sparseArray.indexOf(3)); // 2
console.log(sparseArray.includes(3)); // true

console.log(sparseArray.indexOf(1)); // -1
console.log(sparseArray.includes(1)); // false

console.log(sparseArray.indexOf(undefined)); // -1
console.log(sparseArray.includes(undefined)); // false

在这个示例中,尽管数组是稀疏的,但 indexOf()includes() 方法都能够正确地查找和判断元素的存在与否。需要注意的是,查找 undefined 会返回 -1false,因为这并不表示数组中未定义的元素,而是表示数组中没有 undefined 这个值。如果你想检查数组中是否存在未定义的元素,你需要使用其他方法,如遍历数组并检查元素是否为 undefined

相关文章

网友评论

      本文标题: include 与 indexof

      本文链接:https://www.haomeiwen.com/subject/sofxndtx.html