实现函数deleteArrayElements(),从给定的起始索引i开始从数组中读取N个元素,并删除该子数组中的每个第x个元素。参数startIndex可以大于数组的长度。通过再次从头开始循环遍历数组来实现连续寻址。参数 everyIth 也可以大于数组的长度。然而,至少有一个元素,即子数组的第 0 个元素,应该始终被删除。返回没有被删除元素的数组和被删除元素的数组
function deleteArrayElements(number, startIndex, everyIth) {
let array = [];
let result = [];
let removedItems = [];
if (startIndex > array.length) {
startIndex = startIndex % array.length;
}
for (let i = startIndex; i < startIndex + number; i += everyIth) {
let indexToRemove = i % array.length;
removedItems.push(array[indexToRemove]);
array.splice(indexToRemove, 1);
}
result = array;
return { newResult: result, removedItems: removedItems };
}
预期输出为 {“newResult”:[null,“katze”,null,“elefant”,null,“stachelschwein”,“affe”,“giraffe”],“removedItems”:[“hund”,“maus”,“schlange”] }; 但我得到的输出是: {“newResult”:[“hund”,“katze”,“maus”,“elefant”,“schlange”,“stachelschwein”,“affe”,“giraffe”],“removedItems”:[“hund”,“elefant” ", "affe"]}
使用拼接不会添加
null
来代替已删除的元素。由于 newResult 的长度应该与数组的长度相同,因此使用 Array.map 是一个不错的计划:
let array = ["hund", "katze", "maus", "elefant", "schlange", "stachelschwein", "affe", "giraffe"];
function deleteArrayElements(number, startIndex, everyIth) {
let removedItems = [];
let result = array.map((el, i) => {
if (i >= startIndex && i < startIndex + number && i % everyIth === 0) {
removedItems.push(el);
return null;
} else {
return el;
}
});
return { newResult: result, removedItems: removedItems };
}
console.log(deleteArrayElements(6, 0, 2));