Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9318

ES6メソッドの復習 map(), filter(), findIndex(), test()

$
0
0
ES6の配列メソッド 使わなくても別の構文で書ける シンプルに書ける 実行速度が早いわけではない map() 配列をイテレートする 要素1つずつ処理する 新しい配列を生成する const array = [1, 2, 4, 8]; const resultArray = array.map(x => x * 2) console.log(resultArray) // output: Array [2, 4, 8, 16] const object = { "hoge": {text: "fuga"}, "foo": {text: "bar" }, "fiz": {text: "buzz"} }; const objectToArray = Object.keys(object).map(key => { const value = object[key] value['id'] = key return value }); console.log(objectToArray) /* output: [ { text: 'fuga', id: 'hoge' }, { text: 'bar', id: 'foo' }, { text: 'buzz', id: 'fiz' } ] */ filter() 配列をイテレートする 条件がtrueの要素のみ返す const objectArray = [ { id: "hoge", text: "fuga" }, { id: "foo", text: "bar" }, { id: "fiz", text: "buzz" } ]; const result = objectArray.filter(object => { return object.id === 'hoge' }) console.log(result) // output: [ { id: 'hoge', text: 'fuga' } ] findIndex() 配列をイテレートする 条件がtrueの要素が「何番目なのか」を返す const objectArray = [ { id: "hoge", text: "fuga" }, { id: "foo", text: "bar" }, { id: "fiz", text: "buzz" } ]; const index = objectArray.findIndex(object => { return object.id === 'hoge' }) console.log(index) // output: 0 test() 正規表現を使う マッチする場合、trueを返す マッチしない場合、falseを返す const hoge = "hoge"; const hogefoo = "hogefoo"; const regex = RegExp("hoge*"); console.log(/hoge*/.test(hogefoo)); // true const isHoge = regex.test(hogefoo); // true if (isHoge) { console.log("OK"); } else { console.log("NG"); }

Viewing all articles
Browse latest Browse all 9318

Trending Articles