1、JS判断数组的5种方式
let arr = []
1. instanceof
arr instanceof Array
2. __proto__
arr.__proto__ === Array.prototype
3. constructor
arr.constructor === Array
4. Object.prototype.toString
Object.prototype.toString.call(arr) === '[object Array]'
5. Array.isArray
Array.isArray(arr)
2、js数组遍历
(1)foreach循环
//1 没有返回值
arr.forEach((item,index,array)=>{
//执行代码
})
//参数:value数组中的当前项, index当前项的索引, array原始数组;
//数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
var
ary = [12,23,24,42,1];
var
res = ary.map(
function
(item,index,ary ) {
return
item*10;
})
console.log(res);
//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改
console.log(ary);
//-->[12,23,24,42,1]; 原数组并未发生变化
(3)forof遍历
for
(
var
value of myArray) {
console.log(value);
}
var
arr = [73,84,56, 22,100]
var
newArr = arr.filter(item => item>80)
//得到新数组 [84, 100]
console.log(newArr,arr)
var
arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every(
function
( item, index, array ){
return
item > 3;
}));
false
var
arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.some(
function
( item, index, array ){
return
item > 3;
}));
true
reduce()
方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。var
total = [0,1,2,3,4].reduce((a, b)=>a + b);
//10
reduceRight()
方法的功能和reduce()
功能是一样的,不同的是reduceRight()
从数组的末尾向前将数组中的数组项做累加。var
arr = [0,1,2,3,4];
arr.reduceRight(
function
(preValue,curValue,index,array) {
return
preValue + curValue;
});
// 10
var
stu = [
{
name:
'张三'
,
gender:
'男'
,
age: 20
},
{
name:
'王小毛'
,
gender:
'男'
,
age: 20
},
{
name:
'李四'
,
gender:
'男'
,
age: 20
}
]
function
getStu(element){
return
element.name ==
'李四'
}
stu.find(getStu)
//返回结果为
//{name: "李四", gender: "男", age: 20}
for
(
let
index of [
'a'
,
'b'
].keys()) {
console.log(index);
}
// 0
// 1
for
(
let
elem of [
'a'
,
'b'
].values()) {
console.log(elem);
}
// 'a'
// 'b'
for
(
let
[index, elem] of [
'a'
,
'b'
].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
findIndex 不会改变数组对象。
[1,2,3].findIndex(
function
(x) { x == 2; });
// Returns an index value of 1.
[1,2,3].findIndex(x => x == 4);
// Returns an index value of -1.