gpt4 book ai didi

javascript - 显示数组的前 4 个,然后显示后 4 个

转载 作者:行者123 更新时间:2023-12-02 14:28:32 25 4
gpt4 key购买 nike

我正在尝试找出一种方法来动态地仅显示数组中的前四个元素,就像如何过滤它一样。有 8 项。有没有办法过滤前 4 个。然后当他们单击“下一步”时,它会显示接下来的四个?

$("#test").click(function(){
fruits.splice(0, fruits.length, "Lemon", "Kiwi");
document.getElementById("demo").innerHTML = fruits;
});
$("#next").click(function(){
fruits.next++;
});

function next(number)
{
var index = fruits.indexOf(number);
index++;
if(index >= fruits.length)
index = 0;
return fruits[index];
}

var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

var col1 = ["Banana", "Orange","pies","pretzels"];
var col2 = ["Banana", "Orange"];
document.getElementById("demo").innerHTML = fruits;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Click the button to add and remove elements.</p>
<button id="next" onclick="next();">next</button>
<p id="demo"></p>

最佳答案

您可以使用slice()从数组中选择元素。

var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

$("p").text(fruits.slice(0, 4));
$("button").click(function(){
$("p").text(fruits.slice(4, 8));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<button>Next</button>

关于javascript - 显示数组的前 4 个,然后显示后 4 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com