JS Array的一些方法在实际中很常用,这里整理记录下来,一是为了常常回顾,二也是方便大家
Map
map():返回一个新的Array,每个元素为调用function的结果
语法: array.map(function(currentValue,index,arr), thisValue)
举例:
var numbers = [65, 44, 12, 4], changedValue;
function multiplyArrayElement(num) {
return num * 2;
}
(function myFunction() {
changedValue = numbers.map(multiplyArrayElement);
})()
console.log(changedValue);
Filter
filter():返回一个符合function条件的元素数组
语法: array.filter(function(currentValue,index,arr), thisValue)
举例:
var ages = [32, 33, 16, 40], changedValue;
function checkAdult(age) {
return age >= 18;
}
(function myFunction() {
changedValue = ages.filter(checkAdult);
})()
console.log(changedValue);
Some
some():返回一个boolean,判断是否有元素是否符合function条件
语法: array.some(function(currentValue,index,arr),thisValue)
举例:
var ages = [3, 10, 18, 20], changedValue;
function checkAdult(age) {
return age >= 18;
}
(function myFunction() {
changedValue = ages.some(checkAdult);
})()
console.log(changedValue);
Every
every():返回一个boolean,判断每个元素是否符合function条件
语法: array.every(function(currentValue,index,arr), thisValue)
举例:
var ages = [32, 33, 16, 40], changedValue;
function checkAdult(age) {
return age >= 18;
}
(function myFunction() {
changedValue = ages.every(checkAdult);
})()
console.log(changedValue);
ForEach
forEach():没有返回值,只是针对每个元素调用function
语法: array.forEach(function(currentValue, index, arr), thisValue)
举例:
var numbers = [4, 9, 16, 25],changedValue;
function myFunction(item, index, arr) {
arr[index] = item + 1;
}
numbers.forEach(myFunction);
console.log(numbers);
继续阅读与本文标签相同的文章
-
川航搞起“物流电商” 首家线下体验店开业
2026-05-15栏目: 教程
-
请给三大运营商多一点“爱”
2026-05-15栏目: 教程
-
独家|“爆红视频0带货”作者:不清楚真实转化率 发文初衷只是分享经历
2026-05-15栏目: 教程
-
文在寅:再给我8年,我让韩国成为世界第一!
2026-05-15栏目: 教程
-
清华团队大幅提升事务内存系统性能,获国际顶级会议肯定
2026-05-15栏目: 教程
