arr数组的方法
- 检测数组
Array.isArray(value)
,如果是数组返回true,否则返回false
if (Array.isArray(value)) {
}
- 转换方法
toString
valueOf
toLocaleString
join
var colors = ['red', 'green', 'blue'];
console.log(colors.toString())
console.log(colors.valueOf())
console.log(colors.toLocaleString())
console.log(colors.join())
console.log(colors.join('||'))
- 栈方法
push
pop
var colors = ['red', 'green', 'blue'];
var pushLength = colors.push('yellow', 'green');
console.log(pushLength);
console.log(colors);
var colors = ['red', 'green', 'blue'];
var popitem = colors.pop();
console.log(popitem);
console.log(colors);
- 队列方法
shift
unshift
var colors = ['red', 'green', 'blue'];
var shiftitem = colors.shift();
console.log(shiftitem);
console.log(colors);
var colors = ['red', 'green', 'blue'];
var unshiftitem = colors.unshift('yellow', 'green');
console.log(unshiftitem);
console.log(colors);
- 重排序方法
reverse
sort
var arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr);
var arr = [9, 11, 25, 5, 45]
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
arr.sort();
console.log(arr);
arr.sort(compare);
console.log(arr);
- 操作方法
concat
slice
splice
var colors1 = ['red', 'green', 'blue'];
var colors2 = colors1.concat();
console.log(colors2);
var colors3 = colors1.concat(colors2);
console.log(colors3);
var colors4 = colors1.concat('yellow', ['gray', 'black']);
console.log(colors4);
var colors1 = ['red', 'green', 'blue'];
var colors2 = colors1.slice(1);
console.log(colors2);
var colors3 = colors1.slice(1,2)
console.log(colors3)
var colors1 = ['red', 'green', 'blue'];
var colors2= colors1.splice(0, 1);
console.log(colors2);
console.log(colors1);
var colors1 = ['red', 'green', 'blue'];
var colors2= colors1.splice(0, 1, 'white', 'black');
console.log(colors2);
console.log(colors1);
- 位置方法
indexOf
lastIndexOf
var arr =[1, 2, 3, 4, 5, 4, 3, 2, 1]
var index = arr.indexOf(4)
console.log(index)
var index1 =arr.indexOf(4, 4)
console.log(index1)
var index2 = arr.lastIndexOf(4)
console.log(index2)
var index3 =arr.lastIndexOf(4, 4)
console.log(index3)
- 迭代方法
every
some
filter
map
forEach
var arr = [1,2,3,4,5];
var everyArrF = arr.every(function(item, index, array){
return (item > 3);
})
console.log(everyArrF)
var everyArrT = arr.every(function(item, index, array){
return (item > 0);
})
console.log(everyArrT)
var arr = [1,2,3,4,5];
var someArrT = arr.some(function(item, index, array){
return (item > 3);
})
console.log(someArrT)
var arr = [1,2,3,4,5];
var filterArr = arr.filter(function(item, index, array){
return (item > 3);
})
console.log(filterArr)
var arr = [1,2,3,4,5];
var mapArr = arr.map(function(item, index, array){
return (item * 2);
})
console.log(mapArr)
var arr = [1,2,3,4,5];
var mapArr = arr.forEach(function(item, index, array){
})
- 归并方法
reduce
reduceRight
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;
});
console.log(sum);