1 The `slice()` function returns a shallow copy of a portion of the source 2 array, as specified by the start and end offsets. The original array is 3 not modified. 4 5 If start is omitted or null, it defaults to `0`. If end is omitted or null, 6 it defaults to the length of the source array. 7 8 If either of the offsets is negative, it is treated as counting towards the 9 end of the array. If either value exceeds the array length, it is capped to 10 the length of the array. 11 12 Returns a new array containing the elements copied from the source array. 13 14 Returns `null` if the given input array value is not an array. 15 16 17 -- Testcase -- 18 {% 19 let arr = [ 1, 2, 3, 4, 5 ]; 20 21 print(join("\n", [ 22 // copy all items 23 slice(arr), 24 25 // copy item 3 onwards 26 slice(arr, 3), 27 28 // copy item 2 and 3 29 slice(arr, 1, 3), 30 31 // copy last two items 32 slice(arr, -2), 33 34 // copy items 3 and 4 35 slice(arr, -3, -1) 36 ]), "\n"); 37 %} 38 -- End -- 39 40 -- Expect stdout -- 41 [ 1, 2, 3, 4, 5 ] 42 [ 4, 5 ] 43 [ 2, 3 ] 44 [ 4, 5 ] 45 [ 3, 4 ] 46 -- End -- 47 48 49 Supplying an invalid array will yield `null`. 50 51 -- Testcase -- 52 {% 53 printf("%.J\n", slice("not_an_array", 0, 1)); 54 %} 55 -- End -- 56 57 -- Expect stdout -- 58 null 59 -- End -- 60 61 62 Invalid, non-numeric offset or index values are treated as 0. 63 64 -- Testcase -- 65 {% 66 let arr = [ 1, 2, 3, 4, 5 ]; 67 68 print(join("\n", [ 69 slice(arr, "foo"), 70 slice(arr, "foo", "bar") 71 ]), "\n"); 72 %} 73 -- End -- 74 75 -- Expect stdout -- 76 [ 1, 2, 3, 4, 5 ] 77 [ ] 78 -- End --
This page was automatically generated by LXR 0.3.1. • OpenWrt