0
0

More than 3 years have passed since last update.

reduceメソッドの使い方

Posted at

reduceメソッドの使い方

取得した文字を列を分割した後に、分割された文字に||で区切りを入れたいとする。そのときに役立つのがreduceメソッド。


const text = "ABCDEFGHIJK";

//取得した文字列を1文字づつ分割する。
const textArray = text.split("");

//aは蓄積された文字 bは現在取得している文字
//第2引数に空文字に入れているのは、最初の取得した値はaにはいるので||が効かなくなる為

const result = textArray.reduce(function(a,b){
    return a+'|'+b+'|';
},"")

//|A|B|C|D|E|F|G|H|I|J|K|と表示される。
console.log(result);
0
0
1

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