Jquery只显示数组的前5个元素

时间:2015-10-28 19:29:57

标签: jquery

我有这段代码

var Movies = ['Alice in Wonderland', 'Above Suspicion', 'A Christmas Story', 'A Crack in the Floor', 'A Deadly Encounter ', 'A Deadly Vision'];
var results = $.grep(Movies, function(item){
    for(term in results){
        $("#res").append("<li>" + results[term] + "</li>");
    }

但是它显示了所有元素,我希望它只显示数组的5个元素。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

使用slice()

var Movies = ['Alice in Wonderland', 'Above Suspicion', 'A Christmas Story', 'A Crack in the Floor', 'A Deadly Encounter ', 'A Deadly Vision'];
var results = $.grep(Movies.slice(0, 5), function(item){
for(term in results){
    $("#res").append("<li>" + results[term] + "</li>");
}