Javascript new Array and join() method

后端 未结 5 1834
北恋
北恋 2021-01-13 00:49

Inspired by this popular speech I wanted to figure out some issue related to creating arrays. Let\'s say I am creating new array with:

Array(3)

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 01:30

    join joins the elements together, using what was passed as a joiner. So you have three empty strings "surrounding" the lorems:

    |lorem|lorem|
    

    It might be a little more obvious if you don't use an empty array:

    var arr = [1, 2, 3, 4, 5]; // Like Array(5), except not sparse
    
    arr.join('-and-'); // 1-and-2-and-3-and-4-and-5
    

    And your first example join output, by the way, is incorrect. It should be ,, or ",,". (Depends on the output format.)

提交回复
热议问题