The easiest way to add a new element to an array is using the push method:
unshift()
method adds a new element to an array at the beginning
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined “holes” in an array.
The pop()
method removes the last element from an array:
shift()
method removes the first array element.
The Difference Between Arrays and Objects
- In JavaScript, arrays use numbered indexes.
- In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.
The JavaScript method toString()
converts an array to a string of (comma separated) array values.
The join()
method also joins all array elements into a string:
The concat() method creates a new array by merging (concatenating) existing arrays:
The slice()
method slices out a piece of an array into a new array.
The sort()
method sorts an array alphabetically
and the reverse()
method reverses the elements in an array:
By default, the sort()
function sorts values as strings.
This works well for strings (“Apple” comes before “Banana”).
However, if numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”.
You can fix this by providing a compare function:
Sorting an Array in Random Order:
There are no built-in functions for finding the max or min value in an array.
However, after you have sorted an array, you can use the index to obtain the highest and lowest values.
직접 선형 탐색을 통해 max/min을 찾는 것이 가장 빠른 방법이다.
Sorting an Array in Random Order: