gpt4 book ai didi

javascript - 重新排列数组的更直观方式

转载 作者:行者123 更新时间:2023-12-03 06:51:06 24 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中创建一个函数来重新排列数组的索引。我提出了以下想法,但是使用此方法,我必须为作为方法 reformatArray 的第四个参数给出的数组的每个可能长度创建一个新的 else if 子句。方法中的参数能否以更直观的方式添加?

代码:

function start() {
var array1 = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"];

reformatArray(array1, 1, 2, [1, 2, 0]);
//output should be ["Item 1", "Item 3", "Item 4", "Item 2", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"]
//WORKS

var array2 = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"];

reformatArray(array2, 2, 5, [3, 1, 3, 2]);
//output should be ["Item 1", "Item 2", "Item 6", "Item 4", "Item 6", "Item 5", "Item 8"]
//DOES NOT WORK because array as fourth argument is greater than 3 in length
}

function reformatArray(array, startIndex, numOfIndicesToReplace, newIndicesPositions) {
var newPosLength = newIndicesPositions.length;

if (newPosLength == 0) {
array.splice(startIndex, numOfIndicesToReplace);
} else if (newPosLength == 1) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]]);
} else if (newPosLength == 2) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]], array[startIndex + newIndicesPositions[1]]);
} else if (newPosLength == 3) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]], array[startIndex + newIndicesPositions[1]], array[startIndex + newIndicesPositions[2]]);
}
//etc.
}

提前致谢。

最佳答案

您可以创建要传递给拼接的参数列表并使用 Function.prototype.apply将它们传递给拼接。

function reformatArray(array, startIndex, numOfIndicesToReplace, newIndicesPositions) {
var newPosLength = newIndicesPositions.length;
var params = [startIndex, numOfIndicesToReplace];

newIndicesPositions.forEach(function(val, pos) {
params.push(array[startIndex + newIndicesPositions[pos]])
});

array.splice.apply(array, params);
}

关于javascript - 重新排列数组的更直观方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com