JavaScript のメモ
配列
例:
[1, 2, 3]
配列のコピー
// 参照渡し
let a = [1, 2, 3]
let b = a
b[0] = -1
a // [-1, 2, 3]
// コピー
a = [1, 2, 3]
b = a.slice()
b[0] = -1
a // [1, 2, 3]
b // [-1, 2, 3]
末尾の値
let a = [1, 2, 3]
a.at(-1)
配列を取り出す
let a = [1, 2, 3, 4, 5]
a.slice(2) // [3, 4, 5]
// 注意
a.slice(2, -1) // [3, 4]
数列の作成 (いわゆる range)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
range(0, 10, 1) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for-of
for(let c of ['a', 'b', 'c']){
console.log(c)
}
```js title=”結果” a b c
### map
```js
let a = [1, 2, 3].map(x => x ** 2)
// [2, 4, 6]
すべて零の配列 (zeros)
Array.zeros = (n) => Array.from({ length: n}, () => 0);
Array.zeros(5) // [0, 0, 0, 0, 0]
合計 (sum)
Array.prototype.sum = function(){ return this.reduce((prev, curr) => prev + curr, 0) }
[1, 2, 3, 4].sum() // 10
平均 (mean)
Array.prototype.mean = function(){ return this.reduce((prev, curr) => prev + curr, 0) / this.length }
[1, 2, 3, 4].mean() // 2.5
文字列
例:
"text"
テンプレートリテラル
let a = 100
`${a / 10}` // "10"
数値
例:
1
文字列を数値に変換
parseInt('100') // 100
parseFloat('100.1') // 100.1
フォーマット
// 小数点以下 3 桁
(1.2).toFixed(3) // "1.200"
日付
let today = new Date
today.toDateString() // "Sat Jan 01 2022"
today.toISOString() // "2021-12-31T15:00:00.000Z"
today.toLocaleDateString() // "2022/1/1"
today.toLocaleString() // "2022/1/1 0:00:00"
today.toLocaleTimeString() // "0:00:00"
today.toString() // "Sat Jan 01 2022 00:00:00 GMT+0900 (日本標準時)"
today.toTimeString() // "00:00:00 GMT+0900 (日本標準時)"
today.toUTCString() // "Fri, 31 Dec 2021 15:00:00 GMT"