如何在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
相关产品推荐
相关产品推荐

