数组
基本概念
在其他语言中数组通常用于存放一系列数据类型相同的值。但是在Javascript里面数组可以存放不同类型的值,并且长度不是固定的。
创建数组
var fruits = ['Apple', 'Banana'];
console.log(fruits.length);
通过索引访问数组元素
var first = fruits[0];
// Apple
var last = fruits[fruits.length - 1];
// Banana
遍历数组
fruits.forEach(function (item, index, array) {
console.log(item, index);
});
// Apple 0
// Banana 1
添加元素到数组的末尾
var newLength = fruits.push('Orange');
// newLength:3; fruits: ["Apple", "Banana", "Orange"]
删除数组末尾的元素
var last = fruits.pop(); // remove Orange (from the end)
// last: "Orange"; fruits: ["Apple", "Banana"];
删除数组最前面(头部)的元素
var first = fruits.shift(); // remove Apple from the front
// first: "Apple"; fruits: ["Banana"];
添加元素到数组的头部
var newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"];
找出某个元素在数组中的索引
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
var pos = fruits.indexOf('Banana');
// 1
通过索引删除某个元素
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
// ["Strawberry", "Mango"]
从一个索引位置删除多个元素
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"]
复制一个数组
var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]