数组方法
数组方法两大类,不改变原数组,改变原数组
//以下方法会改变数组
//ES5有七个
push()和pop()互为逆运算
var array = ['a','b','c'];
array.push('d');
console.log(array)//[ 'a', 'b', 'c', 'd' ]
array.pop();
console.log(array);//[ 'a', 'b', 'c' ]
//shift()和unshift()互为逆运算
array.unshift('A');
console.log(array);//[ 'A', 'a', 'b', 'c' ]
array.shift();
console.log(array)//[ 'a', 'b', 'c' ]
//以字符串规则排序
array.push('a');
array.sort();
console.log(array);//[ 'a', 'a', 'b', 'c' ]
//捻接数组
array.splice(star,length,addItems);
array.splice(0,1,'add');
console.log(array);//[ 'add', 'b', 'c' ]
//反转数组
array.reverse();
console.log(array);//[ 'c', 'b', 'a' ]
//ES7新增加两个会改变数组的方法
arrar.copyWithin()
array.fill()
// 以下方法不会改变数组
//以分隔符分隔并返回字符串
console.log(array.join('-'));//a-b-c
//切片并返回一部分
arry.slice([begin[, end]])
console.log(array.splice(0,1));//[ 'a' ]
//将一个数组拼接到数组上,并返回拼接成的新数组
console.log(array.concat([1,2]));//[ 'a', 'b', 'c', 1, 2 ]
注意array.sort()方法,该方法并不能有效排序数组,需要利用系统自带接口来改造该方法
var array = [1,23,1,43,10,3];
array.sort(function(a,b){
return a - b;
});//升序
console.log(array);//[ 1, 1, 3, 10, 23, 43 ]
array.sort(function(a,b){
return b - a;
});//降序
console.log(array);//[ 43, 23, 10, 3, 1, 1 ]
数组检测
1,检测是否为数组
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。当你的脚本在不同窗口之间数据交互时候,这个方法将失去效果。
var ar = [1,2,3];
console.log(ar instanceof Array);
//true
ES6新增的是Array.isArray()来判断是否是数组。
var a = Array.isArray([1]);
//true
2,检测数组为空
直接用(array.length==0)判断;
数组去重
1,利用对象属性名是唯一的,这个特性来去重
function uni(ar){
let obj = {};
let newArray = [];
ar.forEach(item => {
if(obj[item] == undefined){
obj[item] = 'abc';
newArray.push(item)
}
});
return newArray
}
2,ES6 set方法
var ar = [1,1,2,3,2,3,1,3];
var setar = new Set(ar);
console.log(Array.from(setar))
3,indexOf方法
var oldar = [1,1,2,3,2,34,3,2,1,];
var newar = [];
for(var pro of oldar){
var property = pro;
if(newar.indexOf(property)=== -1){
newar.push(property);
}
}
4,ES6 reduce方法
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
}, [])
console.log(myOrderedArray)