简介
在本实验中,我们将探索如何使用 JavaScript 从数组的特定索引处提取值。我们将使用 pullAtIndex()
函数,该函数会改变原始数组,以过滤掉指定索引处的值,并返回被移除的元素。完成本实验后,你将对如何在 JavaScript 中操作数组有深入的理解。
This tutorial is from open-source community. Access the source code
💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版
在本实验中,我们将探索如何使用 JavaScript 从数组的特定索引处提取值。我们将使用 pullAtIndex()
函数,该函数会改变原始数组,以过滤掉指定索引处的值,并返回被移除的元素。完成本实验后,你将对如何在 JavaScript 中操作数组有深入的理解。
要从数组的特定索引处提取特定值,请按以下步骤操作:
node
以开始练习编码。Array.prototype.filter()
和 Array.prototype.includes()
过滤掉不需要的值,并将它们存储在一个名为 removed
的新数组中。Array.prototype.length
设置为 0
,通过重置其长度来改变原始数组。Array.prototype.push()
仅用提取的值重新填充原始数组。Array.prototype.push()
跟踪被移除的值。pullAtIndex
接受两个参数:原始数组和要提取的索引数组。示例用法:
const pullAtIndex = (arr, pullArr) => {
let removed = [];
let pulled = arr
.map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
.filter((v, i) => !pullArr.includes(i));
arr.length = 0;
pulled.forEach((v) => arr.push(v));
return removed;
};
let myArray = ["a", "b", "c", "d"];
let pulled = pullAtIndex(myArray, [1, 3]);
// myArray = [ 'a', 'c' ], pulled = [ 'b', 'd' ]
恭喜你!你已经完成了“从数组的指定索引处提取值”实验。你可以在 LabEx 中练习更多实验来提升你的技能。