Array常用方法
/**
* Created by liyue.
* Email: li.yue@okcoin.com
* Date: 2018/7/22
* Time: 下午12:52
*/
'use strict';
//常用的数组方法
let Array01 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let Array02 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let Array03 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let Array04 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let Array05 = [1, 21, 13, 24, 75, 106, 37, 80, 79, 210];
let Array06 = [1, 9, 1, 2, 10, 16, 72, 48, 39, 14];
let Array07 = [3, 2, 0, 9, 4, 6, 1, 8, 2, 3, 0, 1, 22, 14, 3, 6, 2, 24];
//升序
let rankUp = function (a, b) {
return a - b;//a大于b的时候,返回正数,a在b后面,a小于b的时候,返回负数,a在b前面
};
//降序
let rankDown = function (a, b) {
return b - a;
};
//会影响原数组的方法
let item01 = Array01.pop();
console.log('Array01', Array01);
console.log('item01', item01);
let item02 = Array02.push(1);
console.log('Array02', Array02);
let item03 = Array03.shift();
console.log('Array03', Array03);
console.log('item03', item03);
let item04 = Array04.unshift(1);
console.log('Array04', Array04);
Array05.reverse();
console.log('Array05', Array05);
Array06.sort();
console.log('sorted Array06', Array06);
Array06.sort(rankUp);
console.log('rankUp Array06', Array06);
Array06.sort(rankDown);
console.log('rankDown Array06', Array06);
console.log('Array07', Array07);
Array07.splice(0, 2);//删除前两项
console.log('Array07', Array07);
Array07.splice(0, 0, 3, 2);//在某一位置插入
console.log('Array07', Array07);
Array07.splice(0, 1, 10);//替换某一位置上的某几个item
console.log('Array07', Array07);
//迭代方法
let arr01 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr01.forEach(function (item, index) {
console.log(item, index);
});
arr01.filter(function (item, index) {
if (item % 2 === 0) {
console.log('the item can be divided by 2:', item);
}
});
let itemAllNumber = arr01.every(function (item, index) {
return typeof item === 'number';
});
console.log(itemAllNumber);
let itemSomeDividedBy3 = arr01.some(function (item, index) {
return item % 3 === 0;
});
console.log(itemSomeDividedBy3);
let newArr = arr01.map(function (item, index) {
return item + 2;
});
console.log(newArr);
let newArr01 = arr01.reduce(function (prev, next) {
return prev + next;
});
console.log(newArr01);
//tips: IE8 及以下版本不支持 every, some, map, reduce。
let arr02 = [1, 2, 3, 4, 5];
let arr03 = [6, 7, 8, 9, 10];
let arr04 = ['a', 'c', 'c', 'd', 'e', 'a'];
console.log(Array.isArray(arr02));
console.log(arr02.concat(arr03));
console.log(arr02.concat([1, 2, 3, 4, 5]));//concat的参数可以是数组也可以直接逐个传入数组成员
console.log(arr02.concat(1, 2, 3, 4, 5));
console.log(arr02.join('~'));//返回字符串,且该方法不影响原数组
console.log(arr02);
console.log('1~2~3~4~5'.split('~'));//数组与字符串的相互转换,对应于join方法
console.log(arr03.slice(0, 3));//截取从第一个数组成员开始到第四位前一位的数组片段
console.log(arr03);//不影响原数组
console.log(arr03.indexOf(10));//4
console.log(arr03.lastIndexOf(10));//4
console.log(arr04.lastIndexOf('a'));//5
console.log(arr04.lastIndexOf('c'));//2
网友评论