侧边栏壁纸
  • 累计撰写 12 篇文章
  • 累计创建 4 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

常用JavaScript函数

 劉豐
2022-04-24 / 0 评论 / 0 点赞 / 1,180 阅读 / 1,122 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-24,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

Map

返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
按照原始数组元素顺序依次处理元素
不会对空数组进行检测
不会改变原始数组

// currentValue	必须。当前元素的值
// index	可选。当前元素的索引值
// arr	可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.Map(function(currentValue, index, arr), thisValue)
let array = [5, 4, 2, 14];
let newArr = array.map((item) => {
  return item + 1;
});
console.log(newArr) // [6, 5, 3, 15]

filter

返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
按照原始数组元素顺序依次处理元素
不会对空数组进行检测
不会改变原始数组

// currentValue	必须。当前元素的值
// index	可选。当前元素的索引值
// arr	可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.filter(function(currentValue, index, arr), thisValue)

回调函数中返回值,若返回值为true,这个元素保存到新数组中;若返回值为false,则该元素不保存到新数组中;原数组不发生改变。

let array = [5, 4, 2, 14];
let newArr = array.filter((item) => {
  return item > 5;
});
console.log(newArr) // [14]

forEach

forEach()方法类似于 map(),传入的函数不需要返回值,并将元素传递给回调函数。
forEach() 对于空数组是不会执行回调函数的。
forEach()不会返回新的数组,总是返回undefined.

// currentValue	必须。当前元素的值
// index	可选。当前元素的索引值
// arr	可选。当前元素属于的数组对象
// thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
array.forEach(function(currentValue, index, arr), thisValue)
let array = [5, 4, 2, 14];
let newArr = array.forEach((item,index) => {
  console.log(index,item);
});
//0 5
//1 4
//2 2
//3 14
0
博主关闭了所有页面的评论