Array là kiểu dữ liệu tương tự list của Python, dùng để chứa nhiều object, cú pháp tạo Array giống list Python:
>> let xs = [1,3, "hello"]
undefined
>> xs
Array(3) [ 1, 3, "hello" ]
>> xs.length
3
>> xs.concat([4,5,6])
Array(6) [ 1, 3, "hello", 4, 5, 6 ]
>> xs[2] = 9
9
>> xs
Array(3) [ 1, 3, 9 ]
Biến đổi lần lượt từng phần tử, dùng function để xử lý từng phần tử. Thu được array mới
>> xs.map(function (x) { return x * x })
Array(3) [ 1, 9, 81 ]
Lọc phần tử thoả mãn điều kiện
>> xs.filter(function (x) { return x > 5 })
Array [ 9 ]
Thu các giá trị lại thành 1 giá trị cuối cùng (ví dụ: tính tổng tất cả các số)
>> xs.reduce(function (accumulator, element) { return accumulator + element })
13
Xử lý từng phần tử , không trả về 1 array mới như map
:
>> xs.forEach(function (x) { console.log(x) })
1
3
9
undefined
A.K.A projecteuler problem 1
>> [...Array(1000).keys()].
filter(function (i) { return i % 3 == 0 || i % 5 == 0 }).
reduce(function (sum, i) { return sum + i })
233168
JS có cả Object lẫn Map, cả hai đều có phần giống dict trong Python.
Object để chứa các thông tin liên quan về 1 đối tượng (không dùng để lặp qua các key), trong khi Map dùng để chứa "mapping" (có thể lặp qua các key).
>> let hvn = {"name": "Hung", "age": 28, "skills": {"Python": 5, "JavaScript": 0.2}}
undefined
>> hvn
Object { name: "Hung", age: 28, skills: {…} }
>> hvn.name
"Hung"
>> hvn.age = 27
27
>> hvn.age
27
>> hvn.skills
Object { Python: 5, JavaScript: 0.2 }
>> JSON.stringify(hvn) # like json.dumps in Python
"{\"name\":\"Hung\",\"age\":27,\"skills\":{\"Python\":5,\"JavaScript\":0.2}}"
>> JSON.parse(JSON.stringify(hvn)) # like json.loads in Python
Object { name: "Hung", age: 27, skills: {…} }
>> let rankMap = new Map()
undefined
>> rankMap.set("Python", 5).set("JS", 0.2)
Map { Python → 5, JS → 0.2 }
>> for (var [k,v] of rankMap) { console.log(k, v) }
Python 5
JS 0.2