上一期到时候我们了解到了关于数组的基础内容,现在我们来学习学习关于Array的高级应用。
实例方法
sort :对数组的数据进行排序
var arr = [1, 2, 11, 0, 9];
arr.sort();
function cmp(a,b){
// a.unicode - b.unicode
}
// 给arr乱序
arr.sort(function(){
return Math.random() - 0.5;
})
遍历相关的实例方法
1- forEach 遍历数组: 两个参数
回调函数,该函数有三个参数 当前数组项 , 当前下标, 本数组
回调函数的this指向, 默认指向window
var stu = ['name', 'age', 'gender', 'address'];
var lilei = {
name: 'Lilei',
age: 12,
gender: 'boy',
address: {
country: '中国',
city: '北京'
}
}
//通过遍历stu数组,得到lilei的所有信息
for (var i = 0; i < stu.length; i++) {
console.log(lilei[stu[i]]);
}
stu.forEach(function(item) {
console.log(this[item]);
}, lilei);
2- every : 是否所有元素都满足条件
var scores = [70, 60, 72, 90, 84];
// 判断是否所有的同学都及格
var result = scores.every(function(item, index, array) {
return item >= 60; //满足条件则返回true 否则false
});
console.log(result); // true
3- some :是否至少有一个元素满足条件
var scores = [70, 60, 72, 90, 84];
// 判断是否至少有一个同学的分数是高分(90以上)
result = scores.some(function(item, index, array) {
return item >= 90; //如果有一个满足返回true 否则false
});
console.log(result); //true
4- filter : 过滤,得到满足条件的元素组成的新数组
var scores = [70, 60, 72, 90, 84];
// 得到所有成绩70分以上的分数
var result = scores.filter(function(item, index, array) {
return item > 70;
});
//将满足条件的数据放入一个新数组输出
console.log(result);
5- find : 查找第一个满足条件的元素 ,返回元素本身,如果没有找到,返回undefined
6- findIndex :查找第一个满足条件的元素,返回元素的下标,如果没有找到,返回 -1
var arr = [{
name: 'Tom',
score: 59
}, {
name: 'Lily',
score: 67
}, {
name: 'Jerry',
score: 80
}, {
name: 'Lihua',
score: 90
}];
// 找到第一个及格的学生
var result = arr.find(function(item, index) {
return item.score >= 60;
});
console.log(result);
//返回内容
// 找到第一个及格学生的下标
var index = arr.findIndex(function(item) {
return item.score >= 60;
});
console.log(index);
//返回下标
7- map :映射,将数组的每一项映射成为另外一项
var arr = [1, 2, 6, 8, 9];
// arr中的每一项都翻倍
var newArr = arr.map(function(item, index) {
return item * 2; //将数组内容全部乘2
});
console.log(newArr); //返回新数组
8- reduce: 统计 累计
var arr = [1, 2, 6, 8, 9];
var sum = arr.reduce(function(s, item) {
console.log('回调函数执行');
return s + item;
}, 50); //将数组内容的和加上50
console.log(sum); //输出最后和
以上便是关于数组的全部内容