Array is a data structure used a lot in programming languages and in Javascript is no exception. With the new features introduced in ES6, ES7 makes Javascript even more interesting. In this article, I would like to share the ways / tips used with the array that I have collected.
1. Pass a blank parameter to a function
If you want to execute a function and don’t pass any parameters even though the function has already been defined, then JS will throw an error. For example:
1 2 3 | method('parameter1', , 'parameter3'); Uncaught SyntaxError: Unexpected token , |
The most common solution people use is to pass null or undefined
1 2 3 | method('parameter1', null, 'parameter3') // hoặc method('parameter1', undefined, 'parameter3'); |
But passing null or undefined only solves the problem right now, although it still works, but really if so many parameters make our code redundant and unprofessional. To solve this we can use the spread operators introduced in ES6. Given the properties of the array, we can have an empty element and we can pass that array into the function call.
method(...['parameter1', , 'parameter3']);
2. Create unique values in the array
By using the spread operator
and Set
we can create an array of values with different values.
1 2 3 | const arr = [...new Set([1, 2, 3, 3])]; Kết quả của arr sẽ là: [1, 2, 3] |
3. Map with Array.from ()
Array.from()
is an alternative to the map function in some cases. For example, when using the document.querySelectorAll()
function, the result is Object Like-array, so in order to use the map function, we have to convert it to array. With array.from () we can always make that move.
1 2 3 | const contents = document.querySelectorAll('span.content'); const result = Array.from(contents, c => c.textContent); |
4. Delete the element in the array
To reduce the size of the array or delete n elements in the array, we can use array.length
1 2 3 4 | let array = ['a', 'b', 'c', 'd'] array.length = 2 // Kết quả: array = ["a", "b"] |
5. Get the last element in the array
Array.prototype.slice(begin, end)
is used to trim elements in the array when you pass parameters begin
and end
, otherwise the transmission end
, it will automatically set the value of length
of the array. Because begin
can receive negative values, we can get the last element of the array.
1 2 3 4 5 6 7 | let array = [1, 2, 3, 4, 5, 6] array.slice(-1) // Kết quả: array = [6] array.slice(-2) // Kết quả: array = [5,6] |
Thank you for taking the time to read the article.
Source: Collector