创建数组
var fruits = ['apple', 'banana']
通过索引访问数组元素
var first = fruits[0] var last = fruits[fruits.length - 1]
遍历数组
fruits.forEach(function (item, index, array) {
console.log(item, index);
})
添加元素到数组尾部
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"]
数组的索引是从0开始的,最后一个元素的索引等于该数组的长度减1。如果指定的索引是一个无效值,并不会报错,而是返回undefined
var arr = ['this is the first element', 'this is the second element', 'this is the last element']; console.log(arr[0]); // 打印 'this is the first element' console.log(arr[1]); // 打印 'this is the second element' console.log(arr[arr.length - 1]); // 打印 'this is the last element'
在数组中已数字开头的属性不能用点开头引用
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; console.log(years.0); // 语法错误 console.log(years[0]); // √
renderer.3d.setTexture(model, 'character.png'); // 语法错误 renderer['3d'].setTexture(model, 'character.png'); // √
Length和数组下标的关系
var fruits = []; fruits.push('banana', 'apple', 'peach'); console.log(fruits.length); // 3
fruits[5] = 'mango'; console.log(fruits[5]); // 'mango' console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] console.log(fruits.length); // 6
fruits.length = 10; console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] console.log(fruits.length); // 10
fruits.length = 2; console.log(Object.keys(fruits)); // ['0', '1'] console.log(fruits.length); // 2