JavaScript Arrays
July 9, 2021 · 2 min read
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!
Arrays: An array is a data type that stores data in order.
Defining Arrays and Array Elements #
<script>
// 1. Syntax: use [] to define an empty array
// Define an empty array, then assign it to the variable classes
// let classes = [];
// 2. Define a nonempty array
let classes = ['Xiaoming', 'Xiaogang', 'Xiaohong', 'Xiaoli', 'Xiaomi']
</script>
Accessing Arrays and Array Indexes #
Indexes start at 0.
Array Element Value Types #
As a collection of data, an array can have elements of any data type.
<script>
// 6. Array element values can be of any data type
// a) Array element values are strings
let list = ['HTML', 'CSS', 'JavaScript']
// b) Array element values are numbers
let scores = [78, 84, 70, 62, 75]
// c) Mix several types
let mixin = [true, 1, false, 'hello']
</script>
Array Length Property #
Arrays are not a new data type in JavaScript; they belong to the object type.
<script>
// Define an array
let arr = ['html', 'css', 'javascript']
// An array has a length property that gives its number of elements
console.log(arr.length) // 3
</script>
Working with Arrays #
As objects, arrays have not only a length property but also many methods:
pushdynamically adds an element to the end of an arrayunshitdynamically adds an element to the beginning of an arraypopremoves the last elementshiftremoves the first elementspliceadds or removes elements in an array (this method changes the original array.)splice(startingPosition, numberToDelete)splice(startingPosition, numberToDelete, arrayElementsToAdd)let arr = ['red', 'green', 'blue']arr.Splice (1, 0, 'pink', 'hotpink') // Add pink and hotpink at index 1console.log (arr) // ['red', 'pink', 'hotpink', 'green', 'blue']`
When using the four methods above, each operates directly on the original array: after any method is called successfully, the original array changes accordingly. Adding or removing elements does not cause the length property to become inaccurate.
<script>
// Define an array
let arr = ['html', 'css', 'javascript']
// 1. push dynamically adds an element to the end of an array
arr.push('Nodejs')
console.log(arr)
arr.push('Vue')
// 2. unshit dynamically adds an element to the beginning of an array
arr.unshift('VS Code')
console.log(arr)
// 3. splice dynamically removes any element
arr.splice(2, 1) // Remove 1 element starting at index 2
console.log(arr)
// 4. pop removes the last element
arr.pop()
console.log(arr)
// 5. shift removes the first element
arr.shift()
console.log(arr)
</script>
References
Related readings
If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: