我有var ar = [1, 2, 3, 4, 5]
并想要一些函数getSubarray(array, fromIndex, toIndex)
,调用getSubarray(ar, 1, 3)
的结果是新数组[2, 3, 4]
。
答案 0 :(得分:352)
var ar = [1, 2, 3, 4, 5];
var ar2 = ar.slice(1, 3 + 1); // slice from 1..3 - add 1 as the end index is not included
console.log(ar2);
>>[ 2, 3, 4 ]
答案 1 :(得分:16)
对于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"]
测试1 :
bigArr.subarray(1,-1)
< [“b”,“c”,“fd”,“ze”]
<强>的Test2:强>
bigArr.subarray(2,-2)
&LT; [“c”,“fd”]
<强> Test3的:强>
bigArr.subarray(2)
&LT; [“c”,“fd”,“ze”]
来自其他语言的开发人员可能更容易(.i.e:Groovy)
答案 2 :(得分:5)
var array_one = [11, 22, 33, 44,55];
var start = 1;
var end = array_one.length-1
var array_2 = array_one.slice(start, end);
console.log(array_2)
答案 3 :(得分:0)
问题实际上是要求新数组,因此我认为更好的解决方案是将Abdennour TOUMI's answer与克隆功能结合使用:
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]
使用clone()
功能,您现在可以执行以下操作:
Array.prototype.subarray=function(start, end) {
if(!end){
end = this.length;
}
var newArray = clone(this);
return newArray.slice(start, end);
};
如果没有副本,您将丢失原始数组。
示例:强>
var 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]