数组的常见方法:

创建数组

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

通过索引访问数组元素

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

forEach: 遍历数组

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

push: 加元素到数组的末尾

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

pop: 删除数组末尾的元素

var last = fruits.pop();   // last: "Orange"; fruits: ["Apple", "Banana"];

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

var first = fruits.shift();   // first: "Apple"; fruits: ["Banana"];

unshift: 添加元素到数组的头部

var newLength = fruits.unshift('Strawberry')   // ["Strawberry", "Banana"];

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

var pos = fruits.indexOf('Banana');    // 1

splice: 通过索引删除某个元素

var removedItem = fruits.splice(pos, 1);    // ["Strawberry"]

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

var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
var pos = 1, n = 2;
var removedItems = vegetables.splice(pos, n);
console.log(vegetables);    // ["Cabbage", "Carrot"] 
console.log(removedItems);  // ["Turnip", "Radish"]

concat: 合并两个或多个数组

const array1 = ['Cabbage', 'Turnip'];
const array2 = [ 'Radish', 'Carrot'];
const array3 = array1.concat(array2);
console.log(array3);    // expected output: Array ['Cabbage', 'Turnip', 'Radish', 'Carrot']

every: 测试一个数组内的所有元素是否都能通过某个指定函数的测试

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));  // true

filter: 创建一个新数组, 其包含通过所提供函数实现的测试的所有元素

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);     //["exuberant", "destruction", "present"]

map: 创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);    // [2, 8, 18, 32]

sort: 对数组的元素进行排序,并返回数组

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);  // ["Dec", "Feb", "Jan", "March"]

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);     //[1,2,3,4,5]
posted on 2021-03-13 16:24  李起桉  阅读(59)  评论(0编辑  收藏  举报