Fork me on GitHub

js基础-数组

图片描述


ES5新增的5个数组迭代方法

(1)every():对数组中的每一项给定函数,如果对该函数的每一项都返回true,则返回true.

1
2
3
4
5
6
7
8
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyResult = numbers.every(function(item, index, array) {
return (item > 2);
});
alert(everyResult); //false

(2)some():对数组中的每一项运行给定函数,如果该函数对任一项返回true,则返回true。

1
2
3
4
5
6
7
8
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var someResult = numbers.some(function(item, index, array) {
return (item > 2);
});
alert(someResult); //true

(3)forEach():对数组中的每一项运行给定函数。这个方法没有返回值。

1
2
3
4
var numbers = [1,2,3,4,5,4,3,2,1];
numbers.forEach(function(item, index, array){
//执行某些操作
});

(4)filter():对数组中的每一项运行给定函数,返回该函数会返回true 的项组成的数组。

1
2
3
4
5
6
7
8
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});
alert(filterResult); //[3,4,5,4,3]

(5)map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。

1
2
3
4
5
6
7
8
var numbers = [1,2,3,4,5,4,3,2,1];
var mapResult = numbers.map(function(item, index, array){
return item * 2;
});
alert(mapResult); //[2,4,6,8,10,8,6,4,2]

数组对象和类数组对象的区别

类数组对象:只包含使用从零开始,且自然递增的整数作为键名,并且定义了length表示元素个数的对象,我们就认为它是类数组对象!

js中常见的类数组有arguments()对象和DOM方法的返回结果,如document.getElementsByTagName().

1
2
3
4
5
6
var a = {};
var i = 0;
while(i<10){
a[i] = i*i;
i++;
}

数组对象

1
2
3
4
5
6
var b = [];
var i = 0;
while(i<10){
b[i] = i*i;
i++;
}

其实从源代码上面看没什么区别,但js中支持:
1:类名[属性名称] = 值
2:类名.属性名称 = 值
要是你想在类中使用动态的属性,就必须使用第一个

看看区别:
类数组对象:

1
2
3
4
5
6
7
console.log(typeof a);//object 注意:数组也是对象哦
console.log(a); // Object {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} 很明显对象啊
console.log(a.length); //undefined 区别就在这了 类数组对象没有长度的属性和数组的方法
console.log(Object.prototype.toString.call(a));//[object Object]

数组对象:

1
2
3
4
5
6
7
console.log(typeof b);//object
console.log(b);// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 很明显数组啊
console.log(b.length); //8
console.log(Object.prototype.toString.call(b));//[object Array]

判断一个对象是否属于类数组

1
2
3
4
5
6
7
8
9
10
11
function isArrayLike(o) {
if (o && // o is not null, undefined, etc.
typeof o === 'object' && // o is an object
isFinite(o.length) && // o.length is a finite number
o.length >= 0 && // o.length is non-negative
o.length===Math.floor(o.length) && // o.length is an integer
o.length < 4294967296) // o.length < 2^32
return true; // Then o is array-like
else
return false; // Otherwise it is not
}

由于类数组不具有数组所具有的操作数组的方法,将类数组转换为数组之后就能调用如shift,unshift,splice,slice,concat,reverse,sort等这些强大的方法。

类数组转换为数组的方法

1
2
3
4
Array.prototype.slice.call(arrayLike)
//将arguments转化为数组后,截取第一个元素之后的所有元素
var args = Array.prototype.slice.call(arguments,1);

首先Array.prototype.slice.call(arrayLike)的结果是将arrayLike对象转换成一个Array对象。所以其后面就可以直接调用数组具有的方法,例如:

1
Array.prototype.slice.call(arrayLike).forEach(function(element,index){ //可以随意操作每一个element了 })