Java Reference
In-Depth Information
Slicing an Array
The slice(start, end) method returns an array containing a subarray of the original
array from index between start and end (exclusive). If start and end are negative, they
are treated as start + length and end + length , respectively, where length is the
length of the array. Both start and end are capped between 0 and length (inclusive). If
end is unspecified, it is assumed as length . If start and end (exclusive) include a sparse
range, the resulting subarray will be sparse. Here are examples of using the slice()
method:
var names = ["Fu", "Li", "Su"];
// Assigns ["Li","Su"] to subNames1. end = 5 will be replaced with end = 3.
var subNames1 = names.slice(1, 5);
// Assigns ["Li","Su"] to subNames2. start = -1 is used as start = 1 (-2 + 3).
var subNames12 = names.slice(-2, 3);
var ids = [10, 20,,,30, 40, 40]; // A sparse array
// Assigns [20,,,30,40] to idsSubList whose length = 5
var idsSubList = ids.slice(1, 6);
Splicing an Array
The splice() method can perform insertion, deletion, or both, depending on the
arguments passed. Its signature is:
splice (start, deleteCount, value1, value2,...)
The method deletes deleteCount elements starting at index start and inserts
the specified arguments ( value1 , value2 , etc.) at index start . It returns an array that
contains the deleted elements from the original array. The indexes of the existing
elements after the deletion, insertion, or both are adjusted, so they are contiguous. If
deleteCount is 0, specified values are inserted without deleting any elements. Here are
examples of using the method:
var ids = [10, 20, 30, 40, 50];
// Replace 10 and 20 in the array with 100 and 200
var deletedIds = ids.splice(1, 2, 100, 200);
print("ids = " + ids);
print("deletedIds = " + deletedIds);
 
Search WWH ::




Custom Search