【随時更新】個人的にJavaScriptでよく使う記法まとめ

個人的にJavaScriptでよく使う記法をまとめました

配列

for で回す

1
2
3
4
let cars = ['BMW', 'Volvo', 'Mini']
for (let car of cars) {
console.log(car) // 'BMW'
}

for で回す(index付き)

1
2
3
4
let cars = ['BMW', 'Volvo', 'Mini']
for (let [index, car] of cars.entries()) {
console.log(car) // 'BMW'
}

forEach で回す

1
2
let cars = ['BMW', 'Volvo', 'Mini']
cars.forEach(car => { console.log(car) }) // 'BMW'

値を取り除く

1
2
3
let cars = ['BMW', 'Volvo', 'Mini']
cars = cars.filter(car => { return car !== 'Volvo' })
console.log(cars) // ['BMW', 'Mini']

ある値が含まれるかどうか

1
2
let cars = ['BMW', 'Volvo', 'Mini']
cars.includes('Volvo') // true

逆順にする

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) // 'full_name'
console.log(person[key]) // 'John'
}

キーの配列を作成

1
2
let person = { full_name: 'John', last_name: 'Doe', age: 25 }
Object.keys(person) // ['full_name', 'last_name', 'age']

件数を取得

1
2
let person = { full_name: 'John', last_name: 'Doe', age: 25 }
Object.keys(person).length // 3

ディープコピー

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));
// → '{"b":"foo","c":"bar","a":"baz"}'

const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
ordered[key] = unordered[key];
});

console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'

参考
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

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×