How to easily truncate an array with JavaScript?

后端 未结 6 1247
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 16:09

Linq has a convenient operator method called Take() to return a given number of elements in anything that implements IEnumerable. Is there anything

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 16:53

    If you want to selectively pull elements out of an array, you can use the jQuery.grep method.

    (from the jQuery docs)

    var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
    
    $("div").text(arr.join(", "));
    
    arr = jQuery.grep(arr, function(n, i){
      return (n != 5 && i > 4);
    });
    
    $("p").text(arr.join(", "));
    
    arr = jQuery.grep(arr, function (a) { return a != 9; });
    $("span").text(arr.join(", "));
    

提交回复
热议问题