You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提取数组非连续元素并与另一数组比较,有无更优实现函数?

问题描述

我需要从数组中提取非顺序元素,并与另一数组比较,确认所有提取的元素都属于目标数组。此前用slice处理顺序提取的场景运行正常,代码如下:

let winArray = [playerSymbol, playerSymbol, playerSymbol]
if (playingFielddArray.slice(0, 3).every(v => winArray.includes(v))) {
    // 执行逻辑
}

但处理非顺序提取时,我需要创建大量临时数组来做比较,写法如下,并不满意:

let newArray = [playingFielddArray[0], playingFielddArray[4], playingFielddArray[8]]
if(newArray.every(v => winArray.includes(v))){ 
    // 执行逻辑
}

请问有没有更合适的实现方式?

解决方案

不需要创建临时数组,直接遍历需要检查的索引集合,验证对应位置的元素是否满足条件即可:

方式1:直接内联判断

如果只是单次使用,直接写出索引数组并调用every方法:

if ([0, 4, 8].every(index => winArray.includes(playingFielddArray[index]))) {
    // 执行逻辑
}

方式2:封装工具函数

如果需要多次检查不同索引集合,可以封装成复用函数:

function checkIndicesMatch(sourceArr, indices, targetArr) {
    return indices.every(index => targetArr.includes(sourceArr[index]));
}

// 使用示例
if (checkIndicesMatch(playingFielddArray, [0, 4, 8], winArray)) {
    // 执行逻辑
}

这种方式既避免了临时数组的冗余创建,代码也更简洁易读,执行效率也更高。


内容的提问来源于stack exchange,提问作者Cats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:40:05