how to create a list of span for a given array

后端 未结 3 534
灰色年华
灰色年华 2021-01-21 08:58

Let\'s say I have an object which looks like that:

var users = [\'user1\', \'user2\'];

For this object I would like to create a list of span li

3条回答
  •  攒了一身酷
    2021-01-21 09:47

    You also can use the Array.map method:

    ['user1', 'user2'].map(
        function(a){
            $('').html(a).appendTo($('body')); return a;
        }
    );
    

    Or even shorter:

    $(['user1','user2'].map(function(a){return ''+a+''}).join(''))
     .appendTo('body');
    

    Or even Array.filter ;)

    ['user1', 'user2'].filter(
        function(a){
            $('').html(a).appendTo($('body')); return true;
        }
    );
    

    Or jQuery.each on a jQuery object derived from the Array

    $(['user1', 'user2']).each(
        function(i,a){
            $('').html(a).appendTo($('body')); return true;
        }
    );
    

提交回复
热议问题