我有一个包含用户输入的数组,我想用HTML显示该数组中的最后五个输入:
function display_last_five()
{
var e = "<hr/>";
e += array.slice(Math.max(array.length - 5, 0)) + " ";
document.getElementById('Result').innerHTML = e;
}
我得到的是
Input1,Input2,Input3
我想要什么:
Input1 Input2 Input3
有一种方法可以操纵输出,或者输入存储不正确?
答案 0 :(得分:1)
我将尝试使用Array.join而不是字符串连接。
function display_last_five()
{
var e = "<hr/>";
e += array.slice(Math.max(array.length - 5, 0)).join(" ");
document.getElementById('Result').innerHTML = e;
}
答案 1 :(得分:1)
使用原始JavaScript:
function displayLastFive ( array )
{
// Get the output element
let result = document.getElementById( 'result' );
// Show the last elements of the array, to a maximum of 5 elements
result.innerHTML = `<hr/>${ array.slice( -5 ).join( ' ' ) }`;
}
displayLastFive( [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] );
<div id="result"></div>
答案 2 :(得分:0)
function display_last_five()
{
var e = "<hr/>";
e += array.slice(Math.max(array.length - 5, 0)) + " ";
document.getElementById('Result').innerHTML = e.replace(/,/g, ' '))
}
使用.replace()删除所有“,”并替换为空格
答案 3 :(得分:0)
var array = ["input1","input2","input3","input4","input4","input5","input6","input7"];
var newHTML = [];
var count=0;
for (var i =array.length; i != 0; i--) {
if(count==6) break
newHTML.push(array[i]);
count++
}
$(".element").html(newHTML.join(" "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element"></div>