An array of
The basic concept
In other languages arrays are often used to hold a series of values of the same data type. But in Javascript arrays can hold different types of values, and the length is not fixed.
Create an array
var fruits = ['Apple'.'Banana'];
console.log(fruits.length);
Copy the code
Access an array element by index
var first = fruits[0];
// Apple
var last = fruits[fruits.length - 1];
// Banana
Copy the code
Through the array
fruits.forEach(function (item, index, array) {
console.log(item, index);
});
// Apple 0
// Banana 1
Copy the code
Adds elements to the end of the array
var newLength = fruits.push('Orange');
// newLength:3; fruits: ["Apple", "Banana", "Orange"]
Copy the code
Deletes the element at the end of the array
var last = fruits.pop(); // remove Orange (from the end)
// last: "Orange"; fruits: ["Apple", "Banana"];
Copy the code
Removes the first (header) element of the array
var first = fruits.shift(); // remove Apple from the front
// first: "Apple"; fruits: ["Banana"];
Copy the code
Adds elements to the array header
var newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"];
Copy the code
Find the index of an element in the array
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
var pos = fruits.indexOf('Banana');
/ / 1
Copy the code
Delete an element by index
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
// ["Strawberry", "Mango"]
Copy the code
Removes multiple elements from an index location
var vegetables = ['Cabbage'.'Turnip'.'Radish'.'Carrot'];
console.log(vegetables);
// ["Cabbage", "Turnip", "Radish", "Carrot"]
var pos = 1, n = 2;
var removedItems = vegetables.splice(pos, n);
// this is how to remove items, n defines the number of items to be removed,
// from that position(pos) onward to the end of array.
console.log(vegetables);
// ["Cabbage", "Carrot"] (the original array is changed)
console.log(removedItems);
// ["Turnip", "Radish"]
Copy the code
Copy an array
var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]
Copy the code