JS中Array常用方法总结

1. 检测数组

Array.isArray()

2. 栈方法

push():在数组末尾添加

pop():在数组末尾移除

3. 队列方法

shift(): 移除数组中的第一项

push():在数组末尾添加

var colors = new Array();
colors.push("red","green");
var item = colors.shift();
alert(item);  // "red"

同时使用unshift()和pop()从相反的方向模拟队列,

unshift(): 在数组前端添加项

pop(): 在数组末端移除

var colors = new Array();
colors.unshift("red", "green");
colors.unshift("black"); 
alert(colors);  // "black", "red", "green"
var item = colors.pop();
alert(item);   // "black"

4. 重排序方法

reverse(): 反转数组顺序

sort(): 由于调用的是每项的toString()方法,然后比较得到的字符串,不能满足需求。

var values = [0,1,5,10,15];
values.sort();
alert(values); // 0,1,10,15,5

所以需要重新写个比较函数,比如升序:如果第一个参数应该位于第二个参数之前则返回负数,如果两个参数相等则返回0,如果第一个参数应该位于第二个参数之后则返回正数。

function compare(value1, value2) {
  if (value1 < value2) {
    return -1;
  } else if (value1 > value2) {
    return 1;
  } else {
    return 0;
  }
}
var values = [0,1,5,10,15];
values.sort(compare);
alert(values); // 0,1,5,10,15

4. 操作方法

contcat(): 不会改变原先数组

slice(start, end): 返回包含从 start 到 end(不包括该元素)之间的新的数组,不会影响原始数组。

splice(index, howmany, item1, ......, itemX):可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。始终返回的是含有被删除的元素的数组。(如果没有删除任何项,则返回空数组)。

5. 位置方法

indexOf(searchValue, fromIndex): 从数组开头查找索引

lastIndexOf(searchValue, fromIndex): 从数组末尾查找索引

6. 迭代方法

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

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

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

var numbers = [1,2,3,4,5];
var someResult = numbers.some(function(item, index, array){
   return (item > 2);
});
alert(someResult);  // true
filter(): 对数组中的每一项运行给定函数,则返回该函数会返回true的项组成的数组。
var numbers = [1,2,3,4,5];
var filterResult = numbers.filter(function(item, index, array){
   return (item > 2);
});
alert(filterResult);  // [3,4,5]

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

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

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

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

猜你喜欢

转载自blog.csdn.net/helixue2012/article/details/80498816