The
slicemethod 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. Theslicemethod 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);
myConsoleswould have the value["PS5", "Switch", "PC"].Alright then let's use the
slicemethod in thesliceArrayfunction to return part of theanimarray given the providedbeginSliceandendSliceindices. 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)