title: 數(shù)組-知識總結(jié)
date: 2023-05-8 19:30:00
categories: 知識總結(jié)
tags: 數(shù)組
數(shù)組方法總結(jié)大全
toString()
把數(shù)組轉(zhuǎn)換為字符串用逗號分割
let arr = ['zhansna','lisi','wangwu']
console.log(arr.toString()) // 'zhansna,lisi,wangwu'
join()
將數(shù)組轉(zhuǎn)換為字符串默認值是逗號分割蔓同,根據(jù)入?yún)⒎指?/p>
let arr = ['zhansna','lisi','wangwu']
console.log(arr.join('*')) // 'zhansna*lisi*wangwu'
pop()
刪除數(shù)組最后一個元素饶辙,改變原數(shù)組,返回被刪除數(shù)組
var fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop();
console.log(fruits) // ['Banana', 'Orange', 'Apple']
console.log(x) // "Mango"
push()
在數(shù)組末尾新添加一個元素斑粱,返回數(shù)組的長度
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi");
console.log(fruits) // ["Banana", "Orange", "Apple", "Mango","Kiwi"]
console.log(x) // x 的值是 5
數(shù)組排序
sort()
數(shù)組排序
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
console.log(points) // [1, 5, 10, 25, 40, 100]
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
console.log(points) // [100, 40, 25, 10, 5, 1]
reverse()
數(shù)組反轉(zhuǎn)
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse(); // 反轉(zhuǎn)元素順序
console.log(fruits) // ['Mango', 'Apple', 'Orange', 'Banana']
Math.max()
查找最大值
let arr =[1,2,3,4]
Math.max.apply(null,arr) // 4
Math.min()
查找最小值
let arr =[1,2,3,4]
Math.min.apply(null,arr) // 1
數(shù)組遍歷方法
forEach()
let arr = [1,2,3]
arr.forEach((value,index,arr) =>{
console.log(value,index,arr)
})
map()
遍歷數(shù)組根據(jù) return 生成新的數(shù)組
let arr = [1,2,3]
arr.map((value,index,arr) =>{
return value*2
})
filter()
遍歷數(shù)組弃揽,return 為 true 的情況下返回當(dāng)前項組成新的數(shù)組
let arr = [1,2,3]
arr.map((value,index,arr) =>{
// 當(dāng)為true的情況下回返回 value 組成新的數(shù)組
return value > 2
})
reduce()
數(shù)組迭代器,遍歷數(shù)組 返回值作為入?yún)?最后的返回值輸出
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce((total, value, index, array)=>{
// total 初次為arr[0] value為arr[1]
// 第二次進來為之前return的值 value為接下來的值
console.log(total, value, index, array)
// 45 4 1 [45, 4, 9, 16, 25]
// 49 9 2 [45, 4, 9, 16, 25]
// 58 16 3 [45, 4, 9, 16, 25]
// 74 25 4 [45, 4, 9, 16, 25]
return total + value
});
console.log(sum) // 99
every()
數(shù)組檢查所有數(shù)組值是否通過檢測,不是所有項都為 true 的話為 false
var numbers = [45, 4, 9, 16, 25];
let a = numbers.every((item) => {
return item>18
} )
console.log(a) // false
some()
數(shù)組遍歷,如果有一項滿足為 true 則返回 true
var numbers = [45, 4, 9, 16, 25];
let a = numbers.some((item) => {
return item>18
} )
console.log(a) // true
indexOf()
在數(shù)組中查找有返回下標沒有返回-1
var fruits = ["Apple", "Orange", "Apple", "Mango"];
console.log(fruits.indexOf("ac")) // -1
find()
查找返回滿足的第一個元素沒有返回 undefined
var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(item => item>100);
console.log(first) // undefined