個人的にJavaScriptでよく使う記法をまとめました
配列
for で回す
1 2 3 4
| let cars = ['BMW', 'Volvo', 'Mini'] for (let car of cars) { console.log(car) }
|
for で回す(index付き)
1 2 3 4
| let cars = ['BMW', 'Volvo', 'Mini'] for (let [index, car] of cars.entries()) { console.log(car) }
|
forEach で回す
1 2
| let cars = ['BMW', 'Volvo', 'Mini'] cars.forEach(car => { console.log(car) })
|
値を取り除く
1 2 3
| let cars = ['BMW', 'Volvo', 'Mini'] cars = cars.filter(car => { return car !== 'Volvo' }) console.log(cars)
|
ある値が含まれるかどうか
1 2
| let cars = ['BMW', 'Volvo', 'Mini'] cars.includes('Volvo')
|
逆順にする
1 2
| let cars = ['BMW', 'Volvo', 'Mini'] let cars_sort = cars.reverse();
|
連想配列(JSON)
初期化
1
| for (var member in myObject) delete myObject[member];
|
for で回す
1 2 3 4 5
| let person = { full_name: 'John', last_name: 'Doe', age: 25 } for (let key in person) { console.log(key) console.log(person[key]) }
|
キーの配列を作成
1 2
| let person = { full_name: 'John', last_name: 'Doe', age: 25 } Object.keys(person)
|
件数を取得
1 2
| let person = { full_name: 'John', last_name: 'Doe', age: 25 } Object.keys(person).length
|
ディープコピー
1 2
| let person = { full_name: 'John', last_name: 'Doe', age: 25 } JSON.parse(JSON.stringify(person))
|
Keyで並び替える
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| onst unordered = { 'b': 'foo', 'c': 'bar', 'a': 'baz' };
console.log(JSON.stringify(unordered));
const ordered = {}; Object.keys(unordered).sort().forEach(function(key) { ordered[key] = unordered[key]; });
console.log(JSON.stringify(ordered));
|
参考
https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
配列を csv ファイルとしてダウンロードする
https://code-maven.com/create-and-download-csv-with-javascript
参考
https://www.w3schools.com/js/js_loop_for.asp