I’m working on a challenge that utilizes .slice() so I’m fooling around with it on Repl.it to get a feel for what it does. I have a question in regard to one particular response that I think I understand but I have a sneaking suspicion that I don’t understand this.
So here is the code I’m using.
for(let i = 0; i < arr.length; i++){
var oneArr = arr.slice(i);}
return arr;
}
chunkyArrayInGroups([“a”, “b”, “c”, “d”], 2);
When I console.log (oneArr) this is what I receive:
from MDN: The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end ( end not included ). The original array will not be modified.
As you loop from 0 to 3
arr.slice(0) is [ ‘a’, ‘b’, ‘c’, ‘d’ ] (index 0 to end of array)
arr.slice(1) is [ ‘b’, ‘c’, ‘d’ ]
arr.slice(2) is [ ‘c’, ‘d’ ]
arr.slice(3) is [ ‘d’ ] (index 3 to end of array)
This is all covered in detail on MDN page for array .slice() method
String has a similar slice() method.
when i is 0 arr[i] is ‘a’, a string of one character and ‘a’.slice(0) is ‘a’ (index 0 to end of string)
when i is 1 arr[i] is ‘b’ and ‘b’.slice(1) is an empty string (index 1 to end of string)
Also covered in detail by the MDN
The MDN is a great go-to manual for anyone serious about web development. Topics are explained in great detail and have accompanying examples to demonstrate key concepts. Consider it the READ part of Read-Search-Ask