你如何在JavaScript中反转数组的一部分?

时间:2018-04-10 05:52:44

标签: javascript arrays reverse

var foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

你如何将上述内容变成下面的内容?

var rev = [0, 1, 5, 4, 3, 2, 6, 7, 8, 9];

正如您所看到的,rev只是部分逆转。反向操作从索引2开始,以索引5

结束

只是为了让最终结果更清晰:

var foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

var rev = [0, 1, 5, 4, 3, 2, 6, 7, 8, 9];

4 个答案:

答案 0 :(得分:0)

var foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

从索引2开始复制foo数组的一部分,直到索引6之前:

var bar = foo.slice(2,6);
bar.reverse();

从foo中拼出您想要的部分,并在其位置插入条形码:

foo.splice(2, 4, bar)

展平阵列:

var rev = [].concat.apply([], foo);

答案 1 :(得分:0)

为避免改变原始数组:

function reversePartArray(array, begin, length) {
    array = array.slice();
    array.splice(begin, length, ...array.slice(begin, begin+length).reverse());
    return array;
}
var foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var rev = reversePartArray(foo, 2, 4);
console.log(foo+'');
console.log(rev+'');

function reversePartArray(array, begin, length) {
    array = array.slice();
    array.splice(begin, 0, ...array.splice(begin,length).reverse());
    return array;
}
var foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var rev = reversePartArray(foo, 2, 4);
console.log(foo+'');
console.log(rev+'');

答案 2 :(得分:0)

这是一个很好的旧迭代解决方案:



let foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

let reverse = (array, start, end) => {
  while (start < end) {
    let t = array[start];
    array[start++] = array[end];
    array[end--] = t;
  }
};

reverse(foo, 2, 5);

console.log(foo.toString());
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以只检查值是否已达到所需的反转范围。

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    start = 2,
    end = 5,
    result = array.map((v, i, a) => i >= start && i <= end ? a[end - i + start] : v);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }