Skip to content

Instantly share code, notes, and snippets.

@hvnsweeting
Last active June 26, 2022 09:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hvnsweeting/e26b6367bb0144d4ce3eaa04cfe3b94d to your computer and use it in GitHub Desktop.
Save hvnsweeting/e26b6367bb0144d4ce3eaa04cfe3b94d to your computer and use it in GitHub Desktop.
JavaScript containers - Array | Object | Dict

Array

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 

Các thao tao với array

Tạo ra array từ 2 array

>> xs.concat([4,5,6])
Array(6) [ 1, 3, "hello", 4, 5, 6 ]

Thay đổi giá trị một phần tử của array

>> xs[2] = 9
9
>> xs
Array(3) [ 1, 3, 9 ]

Các biến đổi, lọc phần tử

map

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 ]
filter

Lọc phần tử thoả mãn điều kiện

>> xs.filter(function (x) { return x > 5 })
Array [ 9 ]
reduce

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
forEach

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

Tính tổng các số nhỏ hơn 1000 chia hết cho 3 hoặc 5

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

Object & Map

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).

Object

>> 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 - JavaScript Object Notation

>> 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: {} }

Map

>> 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment