The
slice
method as we have already learned about returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end. Theslice
method does not mutate the original array, but returns a new one.Here's an example:
var myarr = ["PS5", "Switch", "PC", "Xbox"];
var myConsoles = myArr.slice(0, 3);
myConsoles
would have the value["PS5", "Switch", "PC"]
.Alright then let's use the
slice
method in thesliceArray
function to return part of theanim
array given the providedbeginSlice
andendSlice
indices. The function should return an array.
function sliceArray(anim, beginSlice, endSlice) {
// Only change code below this line
// Only change code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
- Answer:
function sliceArray(anim, beginSlice, endSlice) {
return anim.slice(beginSlice, endSlice);
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
console.log(sliceArray(inputAnim, 1, 3)); will display ['Dog', 'Tiger']
Larson, Quincy, editor. “Return Part of an Array Using the slice Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.
Top comments (0)