0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JS 第一引数の配列を第二引数で要素ごとに連結して返す

Posted at

lodashのjoin関数を作ってみた

配列後方毎に連結させる想定でいた

const join = (array, join = ",") => {
  let index = array.length - 1
  let linking = ""
  for (let i = 0; i < index; i++) {
    linking += array[i] + join
  }
  linking += array[index]
  return linking
}

console.log(join(["a", "b", "c"], "~"))
// => a~b~c
~~~

配列前方毎に連結させる方がすっきり書けるっぽい

~~~~javascript
const join = (array, join = ",") => {
  const arrayCopy = [...array]

  //array最初の要素を取り出す
  let linking = arrayCopy.shift()

  for (let i = 0; i < arrayCopy.length; i++) {
    linking += join + arrayCopy[i]
  }

  return linking
}

console.log(join(["a", "b", "c"], "~"))
// => a~b~c
~~~

こんな発想ができるようになりたいなぁ
関数作るのはすごく勉強になる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?