Ser*_*lov 238 javascript arrays
我有var ar = [1, 2, 3, 4, 5]并且想要一些函数getSubarray(array, fromIndex, toIndex),调用的结果getSubarray(ar, 1, 3)是新数组[2, 3, 4].
Ale*_* K. 372
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);Run Code Online (Sandbox Code Playgroud)
Abd*_*UMI 16
对于slice的简单使用,请使用我对Array Class的扩展:
Array.prototype.subarray=function(start,end){
if(!end){ end=-1;}
return this.slice(start, this.length+1-(end*-1));
}
Run Code Online (Sandbox Code Playgroud)
然后 :
var bigArr=["a", "b", "c", "fd", "ze"]
Run Code Online (Sandbox Code Playgroud)
测试1:
bigArr.subarray(1,-1)
Run Code Online (Sandbox Code Playgroud)
<["b","c","fd","ze"]
测试2:
bigArr.subarray(2,-2)
Run Code Online (Sandbox Code Playgroud)
<["c","fd"]
TEST3:
bigArr.subarray(2)
Run Code Online (Sandbox Code Playgroud)
<["c","fd","ze"]
来自其他语言的开发人员可能更容易(.ie:Groovy)
我有 var ar = [1, 2, 3, 4, 5] 并想要一些函数 getSubarray(array, fromIndex, toIndex),调用 getSubarray(ar, 1, 3) 的结果是新数组 [2, 3, 4 ]。
function getSubarray(array, fromIndex, toIndex) {
return array.slice(fromIndex, toIndex+1);
}
Run Code Online (Sandbox Code Playgroud)
let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)
// result: [2,3,4]
Run Code Online (Sandbox Code Playgroud)
Array.prototype.slice()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
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257198 次 |
| 最近记录: |