【发布时间】:2011-11-24 05:00:55
【问题描述】:
我有var ar = [1, 2, 3, 4, 5] 并且想要一些函数getSubarray(array, fromIndex, toIndex),调用getSubarray(ar, 1, 3) 的结果是新数组[2, 3, 4]。
【问题讨论】:
-
你试过slice吗?
标签: javascript arrays
我有var ar = [1, 2, 3, 4, 5] 并且想要一些函数getSubarray(array, fromIndex, toIndex),调用getSubarray(ar, 1, 3) 的结果是新数组[2, 3, 4]。
【问题讨论】:
标签: javascript arrays
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);
【讨论】:
ar 未修改。 console.log(ar);// -> [1, 2, 3, 4, 5]
slice() 方法与splice() 混淆:splice() 会更改原始数组,而slice() 不会。
ar.slice(4, 4);?我想我应该试试:x..
end 大于序列的长度,则切片将一直提取到序列的末尾(arr.length)。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
为了简单地使用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);
测试2:
bigArr.subarray(2, -2);
测试3:
bigArr.subarray(2);
对于来自其他语言(即 Groovy)的开发人员来说可能更容易。
【讨论】:
Array.prototype.contains 到Array.prototype.includes 的著名示例MooTools forcing a rename。
subarray 方法会产生意想不到的结果。 bigArr.slice(1,-1) 返回 ['b','c','fd'],这是您所期望的(-1 从新数组的末尾敲掉一个元素)。但是bigArr.subarray(1,-1) 的返回结果与bigArr.subarray(1) 相同,即从位置1 到bigArr 末尾的everything。您还强制用户始终将负数作为 end 参数。任何end >= -1 都会给出与end === undefined 相同的结果。另一方面,bigArr.slice(1,3) 返回['b','c'],这也是预期的。
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);
【讨论】:
问题实际上是要求一个新数组,所以我相信更好的解决方案是将Abdennour TOUMI's answer与克隆函数结合起来:
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]
【讨论】:
Array.prototype.slice 已经返回了一个副本。 Array.prototype.splice 修改原始数组。
slice 已经返回了一个浅拷贝,因此不需要这个 subarray 实现。但值得一提的是,您已经对内置对象进行了猴子修补,这是一个很大的禁忌。请参阅Abdennour TOUMI's answer 上的 cmets。