如何从数组中获得子数组?

我有var ar = [1, 2, 3, 4, 5],想要一些函数getSubarray(array, fromIndex, toIndex),调用getSubarray(ar, 1, 3)的结果是新数组[2, 3, 4]

436033 次浏览

看看Array.slice(begin, end)

const ar  = [1, 2, 3, 4, 5];


// slice from 1..3 - add 1 as the end index is not included


const ar2 = ar.slice(1, 3 + 1);


console.log(ar2);

为了简单地使用slice,使用我的数组类扩展:

Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};

然后:

var bigArr = ["a", "b", "c", "fd", "ze"];

Test1:

bigArr.subarray(1, -1);

& lt;["b", "c", "fd", "ze"]

Test2:

bigArr.subarray(2, -2);

& lt;(“c”、“fd”)

Test3:

bigArr.subarray(2);

& lt;[“c”,“fd”,“泽”)

对于来自其他语言(即Groovy)的开发人员来说可能更容易。

问题实际上是在请求新数组,所以我认为更好的解决方案是将Abdennour TOUMI的回答与克隆函数结合起来:

function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
const copy = obj.constructor();
for (const attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}


// With the `clone()` function, you can now do the following:


Array.prototype.subarray = function(start, end) {
if (!end) {
end = this.length;
}
const newArray = clone(this);
return newArray.slice(start, end);
};


// Without a copy you will lose your original array.


// **Example:**


const array = [1, 2, 3, 4, 5];
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]


console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]

[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

const array_one = [11, 22, 33, 44, 55];
const start = 1;
const end = array_one.length - 1;
const array_2 = array_one.slice(start, end);
console.log(array_2);

我有var ar =[1,2,3,4,5],想要一些函数 getSubarray(array, fromIndex, toIndex),调用的结果 getSubarray(ar, 1,3)是新的数组[2,3,4].

. getSubarray(ar, 1,3

精确解

function getSubarray(array, fromIndex, toIndex) {
return array.slice(fromIndex, toIndex+1);
}

让我们测试解决方案

let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)


// result: [2,3,4]

Array.prototype.slice()

slice()方法返回数组部分内容的浅拷贝 进入一个从开始到结束选择的新数组对象(不包括end) 其中start和end表示该数组中项目的索引。的 原始数组将不会被修改

基本上,slice让你从数组中选择子数组

例如,让我们以这个数组为例:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

这样做:

console.log(animals.slice(2, 4));

将会得到这样的输出:

// result: ["camel", "duck"]

语法:

slice() // creates a shallow copy of the array
slice(start) // shows only starting point and returns all values after start index
slice(start, end) // slices from start index to end index

见shallow copy reference .