定義
const apple = 'りんご'
let orange = 'みかん'
constは定数、letは変更可能な変数です。
基本的にはconst、上書きしたいときはletを使います。
アロー関数
let appleLength = 0
const addAppleLength = () => {
appleLength += 1
}
一行で済ませたい時は{}なしでreturnします。
const addAppleLength = () => return appleLength += 1
class
class toggle {
constructor () {
this.isOpen = '.is-open'
}
open () {
console.log(this.isOpen)
}
}
const toggleOpen = new toggle()
toggleOpen.open()
配列
Vue.jsなどのフレームワークでも配列の操作はよく使います。
forEach
基本的な配列内の処理にはforEachで済ませます。
const array = ['a', 'b', 'c']
array.forEach(el => { el === 'a'? console.log(true): console.log(false) })
map
forEachに似てますが、新たな配列を返すことができるのが特徴です。
const ary = [1, 2, 3, 4, 5]
const result = ary.map(item => item + 1)
filter
filterは配列から特定の値を削除したいときに使います。
合致してるもの(true)を残し、falseを削除します。
const ary = [1, 2, 3, 4, 5]
const result = ary.filter(item => item !== 5) // [1, 2, 3, 4]
find
特定の値を1つ取り出したいときに使用します。
const ary = ['red', 'green', 'blue']
const result = ary.find(item => item === 'red') // red
findIndex
index、つまり配列の番号を取得したいときに使います。
検索結果が見つからない時は-1を返します。
const ary = ['red', 'green', 'blue']
const redIndex = ary.findIndex(item => item === 'red') // 0
const yellowIndex = ary.findIndex(item => item === 'yellow') // -1
コメント