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

如何遍历对象数组中的嵌套数组,判断坐标是否存在?

解决方案

核心思路

  1. 将输入的字符串坐标转换为数字(目标数组存储的是数字类型,直接用字符串对比会不匹配)
  2. 遍历舰船数组,只要找到任意一个舰船的坐标数组包含目标数字,就返回true,否则返回false

代码实现

// 你的蠕虫舰船数据
const wormShips = [{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}];

function checkHit(inputCoord) {
    // 转换输入为数字
    const target = Number(inputCoord);
    // 过滤无效输入(非两位数字的情况)
    if (isNaN(target) || target < 0 || target > 99) {
        return false;
    }
    // 遍历所有舰船,检查是否命中
    return wormShips.some(ship => {
        // 取出当前舰船的坐标数组(每个对象仅一个键值对)
        const coords = Object.values(ship)[0];
        return coords.includes(target);
    });
}

// 测试示例
console.log(checkHit('23'));  // 输出: true
console.log(checkHit('84'));  // 输出: false
console.log(checkHit('36'));  // 输出: true
console.log(checkHit('abc')); // 输出: false

代码说明

  • Array.some():遍历数组时只要找到符合条件的元素就立即终止遍历,返回true,比遍历全部元素更高效
  • Object.values(ship)[0]:因为每个舰船对象只有一个键值对,直接取第一个值就能拿到对应的坐标数组
  • 额外的输入校验:处理非数字或超出两位数字范围的无效输入,避免错误判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:15:17