我想打印数组的最后一个'n'元素 [英] I want to print the last 'n' elements of an array
问题描述
我正在编写一个JavaScript函数来获取数组的最后n个元素.如果array有6个元素,而用户给出4,则必须返回最后4个元素.如果用户给出的"n"大于数组中元素的数量,则它应返回所有元素.
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.
问题是,如果数组有8个元素并且我给出数字10,结果是:undefined undefined 1 2 3 4 5 6 7 8
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
我只想显示不带"undefined"的数字.
I want to display only the numbers without "undefined".
谢谢
HTML代码
该数组是:
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代码
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] + " ";
}
}
推荐答案
您可以将slice
从末尾算起.然后join
元素用于格式化输出.
You could take slice
with a negative count from the end. Then join
the elements for a formatted output.
一些链接:
var array = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(array.slice(-4).join(' '));
这篇关于我想打印数组的最后一个'n'元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!