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

JavaScript 如何获取数组中指定索引位置对应的元素值

不同语言下的最优实现方案

JavaScript

最优方法是用Array.prototype.map()遍历索引数组直接取值,时间复杂度为O(n)(n为索引数组长度),没有额外冗余操作:

const arr = ["a","b","c","d"];
const indexes = [0,2];
const result = indexes.map(i => arr[i]);
// 输出结果:["a","c"]

如果需要做边界容错(避免索引超出数组范围返回undefined),可以加一层过滤逻辑:

const result = indexes.filter(i => i >= 0 && i < arr.length).map(i => arr[i]);

Python

直接用列表推导式实现即可,语法简洁且性能优异:

arr = ["a","b","c","d"]
indexes = [0,2]
result = [arr[i] for i in indexes]
# 输出结果:["a", "c"]

边界容错版本:

result = [arr[i] for i in indexes if 0 <= i < len(arr)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:24:05