I am writing a JavaScript function to get the last 'n' elements of the array. If array has 6 elements and if user gives 4, it has to return last 4 elements. If user gives ‘n’ which is greater than the number of elements in the array, then it should return all elements.
The problem is if If the array has 8 elements and I give number 10. The result is : undefined undefined 1 2 3 4 5 6 7 8
I want to display only the numbers without "undefined".
Thanks
HTML code
The array is :
1,2,3,4,5,6,7,8 <br> x: <input type="number" id="x" value="2" > <br> <button onclick="elements()"> Get the elements </button> <p id="result"></p> <script src="ex10.js"></script> JavaScript code
var Elements = new Array(1,2,3,4,5,6,7,8); function elements(){ var x = document.getElementById("x").value; for(var i=Elements.length - x; i <=Elements.length-1; i++) { document.getElementById("result").innerHTML += Elements[i] + " "; } }
array.slice(0,-n)undefinedbecause when you declarevar i = Elements.length - xyou will ge negative numbers oniwhenx > Elements.length. So you will access indexes below0on the array (example:Elements[-1]) that will thrown theundefinedvalues.