[removed] nice human readable join of list

前端 未结 7 1681
半阙折子戏
半阙折子戏 2021-01-26 10:11

Having a list (array) of tags [\'tag1\', \'tag2\', \'tag3\'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the

7条回答
  •  走了就别回头了
    2021-01-26 10:27

    An array can be treated as a stack so you can pop the last element and in turn write this

    var last = tags_titles.pop();
    last = tags_titles.length ? ` and ${last}` : last;
    `Content tagged ${tags_titles.join(", ")} ${last}`
    

    The code uses ES6 string templates, which I generally find to be more readable than doing string concatenation in the code. It also utilizes the fact that the pop method essentially performs to operations. Gets the lasst element of the array and mutate the array. That eliminate the need to do the mutation explicitly (using slice)

提交回复
热议问题