I'm having trouble solving this question (the result is always undefined) and I am not sure what I'm doing wrong... any ideas?
Write a function that takes a number and generates a list from 0 to that number.
Use the function to assign a value to the myNumberList
variable so that it has the value of a list going from 0 to 5.
Assign a value to the variable secondLastItem
that should be the second last item of the myNumberList
array.
function listMaker(listLength) {}
var myNumberList = null; // replace with number list created by listmaker
var secondLastItem = null; // replace with second last item
You can try the following way using ES6
's spread operator ( ...
):
function listMaker(listLength) { return [...Array(listLength).keys()]; } var myNumberList = listMaker(10); // If you want the specified number passed as argument to be included as the last item in the array then push it. myNumberList.push(10); console.log(myNumberList);
Here is one way to write it:
function listMaker(number) { var secondToLast; var list = []; for (var i = 0; i <= number; i++){ list.push(i); } secondToLast = list[list.length - 2]; return [list, secondToLast] } var list = listMaker(5)[0]; var secondToLast = listMaker(5)[1] console.log(list + "\\n" + secondToLast);
That is the snippet ^
Here is the jsfiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.