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

JavaScript数组:如何获取两个字符串元素间的元素?

解决数组中获取两个字符串元素之间对象的问题

嘿,你的这个需求很典型,我给你分享两个实用的解决方案,帮你轻松找到两个字符串元素之间的对象:

方案一:先收集所有字符串元素的索引

这个思路是先把数组里所有字符串类型元素的索引都存起来,之后就能直接通过索引区间来截取中间的元素,适合需要多次获取不同区间的场景。

代码示例:

const arr = ["City1", {name:"sds", age:"asd"}, {name:"sweds", age:"accxsd"}, {name:"sdqws", age:"asssd"}, "City2", {name:"test", age:"123"}, "City3"];

// 收集所有字符串元素的索引
const stringIndices = arr.reduce((indices, item, index) => {
  if (typeof item === 'string') {
    indices.push(index);
  }
  return indices;
}, []);

// 比如获取"City1"(索引0)到"City2"(索引4)之间的元素
if (stringIndices.length >= 2) {
  const startPos = stringIndices[0] + 1;
  const endPos = stringIndices[1];
  const targetElements = arr.slice(startPos, endPos);
  console.log(targetElements); // 输出索引1、2、3的对象
}

方案二:遍历过程中实时记录上一个字符串的位置

如果只需要一次遍历处理所有区间的元素,这个方案更高效,不用额外存储所有索引,遇到字符串时就和上一个字符串的位置对比,直接截取中间元素。

代码示例:

const arr = ["City1", {name:"sds", age:"asd"}, {name:"sweds", age:"accxsd"}, {name:"sdqws", age:"asssd"}, "City2", {name:"test", age:"123"}, "City3"];

let lastStringIndex = null;

for (let i = 0; i < arr.length; i++) {
  if (typeof arr[i] === 'string') {
    // 如果已经记录过上一个字符串的位置,就处理中间的元素
    if (lastStringIndex !== null) {
      const targetElements = arr.slice(lastStringIndex + 1, i);
      console.log(`位于${arr[lastStringIndex]}和${arr[i]}之间的元素:`, targetElements);
    }
    // 更新上一个字符串的索引为当前位置
    lastStringIndex = i;
  }
}

方案对比

  • 方案一:适合需要多次查询不同区间的场景,提前存储索引后,后续查询直接用slice就能快速获取,代码可读性高。
  • 方案二:内存占用更低,一次遍历完成所有区间的处理,适合只需要一次性处理所有区间的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:50:32