<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>数组</title>
<script type="text/javascript">
var a1 = [1, 4, 5, 7, 8];
var a2 = new Array(‘b‘, ‘a‘, ‘d‘);
a1.sort(function (i, j) {
return i - j;
});
a2.sort();
console.info(a1);
console.info(a2);
//每一项为true才返回true
var everyRs = a1.every(function (item, index, arr) {
return item > 1;
});
console.info(‘everyRs‘, everyRs);
//返回为true的项
var filterRs = a1.filter(function (item, index, arr) {
return item > 3;
});
console.info(‘filterRs‘, filterRs);
//循环数组,没返回值
a1.forEach(function (item, index, arr) {
console.info(index, ‘>‘, item);
});
//每一项运行指定的函数,每次函数调用结果组成新的数组返回
var mapRs = a1.map(function (item, index, arr) {
return item * 2;
});
console.info(‘mapRs‘, mapRs);
//有一项满足就返回true
var someRs = a1.some(function (item, index, arr) {
return item < 2;
});
console.info(‘someRs‘, someRs);
//其他方法
// push 尾入 pop尾出
//shift 首出 unshift 首入
// sort(function(i,j){})排序 reserve 在现基础返序
//concat 拼接数组返回新数组
//slice 截取数组,返回全新数组
//splice splice(0,1)删除:从index=0删除一个元素
// splice(1,0,‘aa‘,‘bb‘)插入:index=1后面插入2个元素
// splice(1,1,‘replace‘)替换:删除index=1插入一个新元素 == 替换
//indexOf(‘a‘) -1或者a的第一个位置索引
//lastindexOf(‘a‘) -1或者a的最后位置一个所有
//reduce
//reduceRigth
var sum = a1.reduce(function (prev, cur, index, arr) {
//运行arr.length-1次
//prev记录上一次返回值,cur当前值
console.info(‘prev‘,prev);
console.info(‘cur‘,cur);
return cur + prev;
});
console.info(‘sum‘, sum);
</script>
</head>
<body>
</body>
</html>本文出自 “天空海阔” 博客,请务必保留此出处http://ether007.blog.51cto.com/8912105/1420971
javascript数组常用方法,布布扣,bubuko.com
原文地址:http://ether007.blog.51cto.com/8912105/1420971