1、ES3数组方法
增加:(返回值为数组length)
push();
unshift():
去除:(返回值为去除元素)
pop();
shift();
插入、替换、删除:(slice方法返回新数组)
splice( start, num, docus ); 参数:1、开始索引 2、个数 3、....添加元素
slice( start, end); 参数:1、开始索引 2、结束索引 (参数可以是负数)
翻转:
reverse();
转换为字符串:
join( ' ' );
合并数组:(返回新数组)
concat();
排序:
sort(); 数组排列,数组中对象的某属性排列
1. 默认按照UniCode编码来排序
2. 使用sort方法的回调函数来指定排序规则
* 定义回调函数的两个形参a , b
*
* a 相对于 b 位置在前
*
* 如果回调函数的返回值 大于 0,交换位置
*
* 如果返回值 小于 0 ,不交换位置
*
* 如果返回值 等于 0,保持相对位置
self.data.sort( function( a, b ) {
return a[ sortBy ] > b[ sortBy ] ? -sortKey : sortKey;
} );
2、ES5数组方法
forEach():
第
1个是遍历的数组内容;第
2个是对应的数组索引,第
3个是数组本身
[].forEach(
function(value, index, array) {
});
forEach除了接受一个必须的回调函数参数,还可以接受一个可选的上下文参数(第
2个参数)
array.forEach(callback,[ thisObject])
var database = {
users: [
"张含韵",
"江一燕",
"李小璐"],
sendEmail:
function (user) {
if (
this.isValidUser(user)) {
console.log(
"你好," + user);
}
else {
console.log(
"抱歉,"+ user +
",你不是本家人");
}
},
isValidUser:
function (user) {
return /^张/.test(user);
}
};
database.users.forEach(
database.sendEmail,
database
);
手动实现:foreach方法:
if (
typeof Array.prototype.forEach !=
"function") {
Array.prototype.forEach =
function (fn, context) {
for (
var k =
0, length =
this.length; k < length; k++) {
if (
typeof fn ===
"function" &&
Object.prototype.hasOwnProperty.call(
this, k)) {
fn.call(context,
this[k], k,
this);
}
}
};
}
注意:如果这第
2个可选参数不指定,则使用全局对象代替(在浏览器是为window),严格模式下甚至是
undefined
map():
是原数组被“映射”成对应新数组
[].map(
function(value, index, array) {
});
var data = [
1,
2,
3,
4];
var arrayOfSquares = data.map(
function() {});
手动实现map方法:
if (
typeof Array.prototype.map !=
"function") {
Array.prototype.map =
function (fn, context) {
var arr = [];
if (
typeof fn ===
"function") {
for (
var k =
0, length =
this.length; k < length; k++) {
arr.push(fn.call(context,
this[k], k,
this));
}
}
return arr;
};
}
filter():返回值为新数组
array.
filter(callback,[ thisObject]);
some():返回值为
true或
false
array.
some(callback,[ thisObject]);
every():返回值为
true或
false
array.
every(callback,[ thisObject]);
3、数组检测
Array.isArray();
[] instanceof Array
Object.toString.call( arr ).slice(8,-1);
arr.constructor;//Array