dorkahemp972157683
2018-09-09 14:10
浏览 127

Javascript自动增量数组

Is there a shorthand way to auto increment a Javascript array like you can in PHP?

PHP Example:

$myArray=[];
$myArray[] = [ 'item1' , 'item2' ];
$myArray[] = [ 'item3' , 'item4' ];

JS Example:

let myArray = [];
myArray[ myArray.length ] = [ 'item1' , 'item2' ];
myArray[ myArray.length ] = [ 'item3' , 'item4 '];
//or
myArray.push( [ 'item1' , 'item2' ] );
myArray.push( [ 'item3' , 'item4' ] );

Without using myArray.length or myArray.push()

图片转代码服务由CSDN问答提供 功能建议

是否有像PHP一样自动递增Javascript数组的简便方法? \ n

PHP示例:

  $ myArray = []; 
 $ myArray [] = ['item1','item2']; 
 $ myArray []  = ['item3','item4']; 
   
 
 

JS示例:

  let myArray = []  ; 
myArray [myArray.length] = ['item1','item2']; 
myArray [myArray.length] = ['item3','item4']; 
 //或
myArray.push(['item1  ','item2']); \'nmyArray.push(['item3','item4']); 
   
 
 

不使用 myArray.length或myArray.push()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doufu8588 2018-09-09 14:47
    已采纳

    Here is the ES6 way, using spread operator

    const arr1 = [1,2,3];
    const arr2 = [3,4,5];
    const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]
    

    OR

    just by using the concat method

    const arr1 = [1,2,3];
    const arr2 = [3,4,5];
    const arr3 = arr1.concat(arr2); // arr3 ==> [1,2,3,3,4,5]
    
    点赞 评论
  • duangekui7451 2018-09-09 14:24

    There is certainly a way to do exactly the same thing; it even has similar construction:

    let arr = ['a', 'b'];
    arr = arr.concat([['c', 'd']]);//['a', 'b', ['c', 'd']]
    

    PHP:

    <?php
    $arr = ["a", "b"];
    $arr[] = ["c", "d"];
    print_r($arr);
    ?>
    
    Array
    (
        [0] => a
        [1] => b
        [2] => Array
            (
                [0] => c
                [1] => d
            )
    )
    
    点赞 评论
  • drogon982007 2018-09-09 15:46

    Beside the given answers, you could use Array#splice with a great value for adding the values to the end of the array.

    var array = [];
    
    array.splice(Infinity, 0, ...['item1', 'item2']);
    array.splice(Infinity, 0, ...['item3', 'item4']);
    
    console.log(array);

    </div>
    
    点赞 评论

相关推荐 更多相似问题