JavaScript的 Array 对象是用于构造数组的全局对象,数组是类似于列表的高阶对象。

创建数组

1 var fruits = ['Apple', 'Banana'];
2 
3 console.log(fruits.length);
4 // 2

 通过索引访问数组元素

1 var first = fruits[0];
2 // Apple
3 
4 var last = fruits[fruits.length - 1];
5 // Banana

遍历数组

1 fruits.forEach(function (item, index, array) {
2     console.log(item, index);
3 });
4 // Apple 0
5 // Banana 1

添加元素到数组的末尾

1 var newLength = fruits.push('Orange');
2 // newLength:3; fruits: ["Apple", "Banana", "Orange"]

删除数组末尾的元素

1 var last = fruits.pop(); // remove Orange (from the end)
2 // last: "Orange"; fruits: ["Apple", "Banana"];

删除数组最前面(头部)的元素

1 var first = fruits.shift(); // remove Apple from the front
2 // ["Banana"];

添加元素到数组的头部

1 var newLength = fruits.unshift('Strawberry') // add to the front
2 // ["Strawberry", "Banana"];

找出某个元素在数组中的索引

1 fruits.push('Mango');
2 // ["Strawberry", "Banana", "Mango"]
3 
4 var pos = fruits.indexOf('Banana');
5 // 1

通过索引删除某个元素

1 var removedItem = fruits.splice(pos, 1); // this is how to remove an item
2 
3 // ["Strawberry", "Mango"]

从一个索引位置删除多个元素

 1 var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
 2 console.log(vegetables); 
 3 // ["Cabbage", "Turnip", "Radish", "Carrot"]
 4 
 5 var pos = 1, n = 2;
 6 
 7 var removedItems = vegetables.splice(pos, n);
 8 // this is how to remove items, n defines the number of items to be removed,
 9 // from that position(pos) onward to the end of array.
10 
11 console.log(vegetables); 
12 // ["Cabbage", "Carrot"] (the original array is changed)
13 
14 console.log(removedItems); 
15 // ["Turnip", "Radish"]

复制一个数组

1 var shallowCopy = fruits.slice(); // this is how to make a copy 
2 // ["Strawberry", "Mango"]

数组的常用方法

 1 arrayObj.join();//把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。
 2 
 3 arrayObj.pop();//删除并返回数组的最后一个元素
 4 
 5 arrayObj.push();//向数组的末尾添加一个或更多元素,并返回新的长度。
 6 
 7 arrayObj.reverse();//颠倒数组中元素的顺序。
 8 
 9 arrayObj.shift();//删除并返回数组的第一个元素
10 
11 arrayObj.slice();//从某个已有的数组返回选定的元素
12 
13 arrayObj.sort();//对数组的元素进行排序
14 
15 arrayObj.splice();//删除元素,并向数组添加新元素。
16 
17 arrayObj.toSource();//返回该对象的源代码。
18 
19 arrayObj.toString();//把数组转换为字符串,并返回结果。
20 
21 arrayObj.toLocaleString();//把数组转换为本地数组,并返回结果。
22 
23 arrayObj.unshift();//向数组的开头添加一个或更多元素,并返回新的长度。
24 
25 arrayObj.valueOf();//返回数组对象的原始值

参考地址1:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

参考地址2:https://blog.csdn.net/damon_t/article/details/77006828

参考地址3:http://www.w3school.com.cn/jsref/jsref_obj_array.asp

猜你喜欢

转载自www.cnblogs.com/xialiming/p/javascript_array.html