我在Javascript中有一个数组,如下所示:
var v = new Array("a","b","c","d","e","f"...);
我想反转它但保留前两个元素,所以它会变成:
"a","b",...."f","e","d","c"
我怎样才能做到这一点?
我在Javascript中有一个数组,如下所示:
var v = new Array("a","b","c","d","e","f"...);
我想反转它但保留前两个元素,所以它会变成:
"a","b",...."f","e","d","c"
我怎样才能做到这一点?
v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]
function reverseArrayFromThirdElement(array, copy) {
var arrayCopy = copy ? array.concat() : array;
return [array[0], array[1]].concat(
(arrayCopy.splice(0, 2), arrayCopy.reverse())
);
}
它允许您选择是否要保护阵列不被切片。copy
如果您希望在内部复制数组,则传递为 true。
它像 C# 中的 Array.Reverse 一样工作:
const arrayReverse = (arr, index, length) => {
let temp = arr.slice(index, index + length);
temp.reverse();
for (let i = 0, j = index; i < temp.length, j < index + length; i++, j++) {
arr[j] = temp[i];
}
return arr;
};
例子:
let test = ['a', 'b', 'c', 'd', 'e', 'f'];
test = arrayReverse(test, 4, 2);
console.log(test); // returns [ 'a', 'b', 'c', 'd', 'f', 'e' ]
对于就地反转,这可以使用splice方法完成:
let alp = new Array("a","b","c","d","e","f");
alp.splice(2,4,...alp.slice(2).reverse());
console.log(alp);