1. 本际云推荐 - 专业推荐VPS、服务器,IDC点评首页
  2. 云主机运维
  3. VPS运维

JavaScript数组的9个方法示例

JavaScript数组的九种不同方法

我是本际云服务器推荐网的小编小本本,今天为大家汇总JavaScript数组的9种不同方法,并将详细示例展示给大家。

JavaScript数组的9个方法示例

map

这种方法代表返回一个新的数组,且数组中的每一项都是执行过map提供的回调函数结果。

实现代码如下:

const map = (array, fun) => {
  // 类型约束
  if (Object.prototype.toString.call(array) !== '[object Array]')
    throw new TypeError(array + ' is not a array')
  if (typeof fun !== 'function') throw new TypeError(fun + ' is not a function')
  // 定义一个空数组,用于存放修改后的数据
  let res = []
  for (let i = 0; i < array.length; i++) {
    res.push(fun(array[i]))
  }
  return res
}
// 测试
let res = map([1,2,3],item => { return item * 2 })
console.log(res)//[2,4,6]

filter

这个方法也是返回一个新的数组,但不同的是这个数组中的值是满足filter提供的回调函数的值。

实现代码如下:

const filter = (array, fun) => {
  // 类型约束
  if (Object.prototype.toString.call(array) !== '[object Array]')
    throw new TypeError(array + ' is not a array')
  if (typeof fun !== 'function') throw new TypeError(fun + ' is not a function')
  // 定义一个空数组,用于存放符合条件的数组项
  let res = []
  for (let i = 0; i < array.length; i++) {
    // 将数组中的每一项都调用传入的函数,如果返回结果为true,则将结果push进数组,最后返回
    fun(array[i]) && res.push(array[i])
  }
  return res
}
// 测试
let res = filter([1,2,3],item => {
  return item > 2
})
console.log(res)// [3]

some

这是判断数组中的每一项,当有一项满足回调函数中条件就返回true都不满足则返回false。

实现代码如下:

const some = (array, fun) => {
  // 类型约束
  if (Object.prototype.toString.call(array) !== '[object Array]')
    throw new TypeError(array + ' is not a array')
  if (typeof fun !== 'function') throw new TypeError(fun + ' is not a function')
  let flag = false
  for (let i of array) {
    if (fun(i)) {
      flag = true
      break
    }
  }
  return flag
}
let res = some([1,2,3], item => {
  return item > 2
})
console.log(res)// true

every

这也是判断数组中的每一项,只是它表示的是如果所有项满足回调函数中条件就返回true,否则返回false。

实现代码如下:

const every = (array, fun) => {
  // 类型约束
  if (Object.prototype.toString.call(array) !== '[object Array]')
    throw new TypeError(array + ' is not a array')
  if (typeof fun !== 'function') throw new TypeError(fun + ' is not a function')
  let flag = true
  for (let i of array) {
    if (!fun(i)) {
      flag = false
      break
    }
  }
  return flag
}
let res = every([1,2,3], item => {
  return item > 0
})
console.log(res)// true

reduce

这个就是让数组中的每个元素执行我们提供的回调函数,并将结果汇总返回。

实现代码如下:

const reduce = (array, fun, initialValue) => {
// 类型约束
if (Object.prototype.toString.call(array) !== '[object Array]')
throw new TypeError(array + ' is not a array')

原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7390.html