如何使用 .includes() 进行数组搜索

Javascript教程 2025-11-07

本文将探讨 JavaScript 的 `.includes()` 方法在数组搜索中的应用,包括游戏开发中的实际应用。您将学习到提升自身项目水平的编码技巧!

.includes()

什么是 .includes(),Array.prototype.includes()是 JavaScript 内置的数组方法,用于检查数组是否包含特定元素。如果找到该元素,则返回 true;否则返回 false。

句法:

  • 元素:要查找的值。

  • f* romIndex(可选) *:数组中要开始搜索的位置。

元素:要查找的值。

f* romIndex(可选) *:数组中要开始搜索的位置。

array.includes(element, fromIndex)

.includes() 的作用

这种.includes()方法非常适合检查数组是否包含特定值——它甚至适用于表情符号!为了简单演示,以下是我如何.includes()在吃豆人项目中使用它来检查特定水果。正如你所看到的,苹果返回了,true因为它包含在数组中(实际上,数组中有两个苹果),而西瓜返回了,false因为它不在fruitBonus数组中。

// Example from my Pac-Man project
const fruitBonus = ['🍒','🍓','🍊','🍊','🍎','🍎','🍈','🍈','🚀','🔔','🔑'];

console.log(fruitBonus.includes('🍎')); // true
console.log(fruitBonus.includes('🍉')

重要提示:使用 `.` 存在一些限制.includes()。虽然它对数字、字符串和表情符号等基本类型值非常有效,但它无法对嵌套数组或对象进行深度比较。使用`.` 处理.includes()数组或对象时,仅当引用完全匹配时才会返回结果true,而不会返回内容是否相同的结果。对于深度比较,您需要采用其他方法,例如使用.some()自定义比较函数。

充分利用 .includes()

我成功地.includes()改进了 JavaScript 版吃豆人游戏中幽灵的移动方式!我创建了一个数组,其中包含游戏棋盘上所有交叉路口的索引,并用它.includes()来检测幽灵何时进入交叉路口。这样,幽灵就能在正确的位置改变方向,就像原版街机游戏一样。

intersectionIndices 数组:

export const intersectionIndices = [

    34, 49,
    
    141, 146, 149, 152, 155, 158, 161, 166,
    
    230, 245,

    320, 323,

    377, 378,

    398, 401, 410, 413,

    485, 494,

    566, 569, 578, 581,

    650, 653, 656, 659, 662, 665,

    731, 752,

    824, 827

];

添加交叉点

在棋盘构建过程中,索引列中的方格intersectionIndices会被赋予“交集”类别。这在视觉上和逻辑上都表明这些方格是游戏逻辑中的交集。

export function buildTheBoard() {
  for(let i = 0; i < 868; i++) {
    let div = document.createElement("div");
    gameGrid.appendChild(div);  
    squares.push(div);
    squares[i].classList.add('game-board-square');  

    if (intersectionIndices.includes(i)) {
      squares[i].classList.add('intersection');
    }    
  }    
}

下面,您可以看到intersectionIndices数组中包含的所有交集,这要归功于“intersection”类:

辅助交叉函数

这是一个用于游戏逻辑的简单辅助函数,它接受一个索引作为参数,使用 `is` 函数.includes(),并返回true指定的索引是否为交集:

// Helper function to check if a given index is an intersection
function isIntersection(index) {
  return intersectionIndices.includes(index);
}

使用 .includes() 改进了幽灵移动。

现在我有了检测交叉路口的函数,就可以用它来查看幽灵的当前索引是否包含交叉路口。一旦幽灵进入交叉路口,我就触发方向改变——让幽灵更智能!

工作原理:每个幽灵都会按照定时器自动移动。每走一步,代码都会检查幽灵是否位于十字路口(使用 isIntersection 和 .includes())。如果幽灵位于十字路口:

  • 代码会找出哪些方向是可能的(没有被墙壁或其他幽灵阻挡)。

  • 这样可以避免鬼魂立即掉头(除非卡住,否则不会掉头)。

  • 它随机选择一个有效方向并更新幽灵的移动。

代码会找出哪些方向是可能的(没有被墙壁或其他幽灵阻挡)。

这样可以避免鬼魂立即掉头(除非卡住,否则不会掉头)。

它随机选择一个有效方向并更新幽灵的移动。

// Ghost movement logic uses isIntersection to trigger intersection behavior
export function moveGhost(ghost) {
  const directions = [-1, 1, 28, -28];
  let direction = ghost.direction || directions[Math.floor(Math.random() * directions.length)];

  ghost.timerId = setInterval(function() {
    // ...existing movement logic...

    // At intersections, choose a new direction
    if (isIntersection(ghost.currentIndex)) {
      const reverseDir = ghost.previousIndex - ghost.currentIndex;
      let validDirections = directions.filter(dir => {
        if (dir === reverseDir) return false;
        const nextIndex = ghost.currentIndex + dir;
        return (
          !squares[nextIndex].classList.contains('ghost') &&
          !squares[nextIndex].classList.contains('lairText') &&
          !squares[nextIndex].classList.contains('wall') &&
          !(dir === 28 && squares[nextIndex].classList.contains('lairWall')) &&
          (nextIndex !== 375) &&
          (nextIndex !== 380)
        );
      });

      if (validDirections.length === 0) {
        validDirections = [reverseDir];
      }

      if (validDirections.length > 0) {
        direction = validDirections[Math.floor(Math.random() * validDirections.length)];
        ghost.direction = direction;
      }
    }

    // ...rest of movement logic...
  }, ghost.speed);
}

通过使用 JavaScript 的 .includes() 函数检查代码交叉点,我确保幽灵只在正确的位置改变方向。这使我的项目更接近原汁原味的街机体验,并创造了更真实、更具挑战性的游戏玩法!

JS Pac-Man 项目链接:

🔗已部署项目的链接

🔗GitHub链接

结论

JavaScript 的 `get_object()`.includes()方法用于检查数组是否包含特定元素,true如果包含则返回 true,false如果不包含则返回 false。它非常适合验证数组是否具有特定值,但也有其局限性。虽然它适用于数字、字符串或(在我的项目中)表情符号等简单值,但它无法检查嵌套数组或对象内部是否存在元素。

通过在我的吃豆人游戏中控制幽灵的函数中利用.includes()这一点,我可以判断幽灵的当前索引何时进入十字路口,并触发方向改变。这使得幽灵更加智能,也让我的项目更接近原版街机体验!

就像我之前用.includes()交叉数组来改进游戏逻辑一样,你也可以找到创造性的方法,将这种方法与你自己的数据结构结合起来。探索如何.includes()简化检查并增强项目中的功能——多做实验,看看你能构建出哪些巧妙的解决方案!