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

如何在JavaScript中快速简便地访问嵌套数组的第n个字母?

快速访问嵌套数组中第n个字母的方法

针对你给出的嵌套层级较深的JavaScript数组,有两种简便方法可以快速访问第n个字母:

方法一:提前扁平化数组(推荐多次访问场景)

先把所有字母提取到一个一维数组里,之后直接通过索引访问,后续查询都是O(1)的高效操作:

// 提取所有字母到一维数组
const flattenLetters = (text) => {
  const letters = [];
  text.forEach(block => {
    block.line.forEach(line => {
      line.words.forEach(wordItem => {
        wordItem.word.forEach(charItem => {
          letters.push(charItem.letter);
        });
      });
    });
  });
  return letters;
};

// 使用示例
const flatLetters = flattenLetters(text);
console.log(flatLetters[0]);  // 输出 'H'
console.log(flatLetters[11]); // 输出 'o'

方法二:直接遍历查找(适合单次访问场景)

如果不想提前存储所有字母,可以写一个函数,遍历过程中计数到目标n时返回对应字母:

const getNthLetter = (text, n) => {
  let currentIndex = 0;
  for (const block of text) {
    for (const line of block.line) {
      for (const wordItem of line.words) {
        for (const charItem of wordItem.word) {
          if (currentIndex === n) {
            return charItem.letter;
          }
          currentIndex++;
        }
      }
    }
  }
  return undefined; // n超出字母总数时返回undefined
};

// 使用示例
console.log(getNthLetter(text, 0));  // 输出 'H'
console.log(getNthLetter(text, 11)); // 输出 'o'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:30:09