js数组方法

一些常见的数组方法

// 1.添加元素

// push
// 将一个或者多个元素添加至数组末尾处,并返回数组长度。
{
  let arr = [1, 2, 3, 4]
  let length = arr.push(5, 6)
  console.log(length, arr) // => 6 [1,2,3,4,5,6]
}

// unshift
// 将一个或多个元素添加到数组到开头,并返回数组长度
{
  let arr = [1, 2, 3, 4]
  let length = arr.unshift(0, 6)
  console.log(length, arr) //=> 6 [ 0, 6, 1, 2, 3, 4 ]
}

//2. 删除元素

// pop
// 从数组中删除最后一个元素,若对空数组调用 pop 则返回 undefined ,会更改源数组。
// 返回的是删除的那个元素
{
  let arr = [1, 2, 3, 4, 5]
  let delValue = arr.pop()
  console.log(delValue, arr) //=> 5 [ 1, 2, 3, 4 ]
}

// shift
// 删除数组中第一个元素,若空数组返回 undefined ,会更改源数组。
// 返回被删除的那个元素
{
  let arr = [1, 2, 3, 4]
  let delValue = arr.shift()
  console.log(delValue, arr) //=> 1 [ 2, 3, 4 ]
}

// delete
// 删除数组元素,删除的元素会变成 undefined , 很少使用。
// 返回布尔值,删除成功为true
{
  let temp = [123, 456, 789]
  var delValue = delete temp[1]
  console.log(temp.length, temp[1], temp, delValue) // 3, undefined
}

//3. 替换、删除、指定位置添加

// splice
// 一个功能强大的函数,它可以通过删除/替换/添加,的方式修改数组,并返回修改的内容(以数组的格式),会对元素组进行修改。

// 第一个参数:整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
// 第二个参数:要删除的项目数量。如果设置为 0,则不会删除项目。
// 第三个参数:向数组添加的新项目。
{
  //替换
  let temp = [123, 456, 789]
  let m = temp.splice(1, 1, 'th')
  console.log(m) // [456]
  console.log(temp) //[123,'th',789]

  //删除
  let temp1 = [123, 456, 789]
  let n = temp1.splice(0, 1)
  console.log(n) //[123]
  console.log(temp1) //[456,789]

  //添加
  let temp2 = [123, 456, 789]
  let x = temp2.splice(2, 0, 'tj')
  console.log(x) //[]
  console.log(temp2) //[123,456,'tj',789]
}

//4. 拷贝数组

// slice
// 浅拷贝了原数组,返回一个新的数组对象,原数组不会发生变化。
// 返回一个新的数组,包含从 start 到 end (不包括该元素)的 数组中的元素。
// 如果参数是小数,那么会把小数进行向下取整后,再进行拷贝
// 如果参数不是数字类型,会基于Number()方法进行转换后,载拷贝,如果转换后不是数字,则返回原数组

// 第一个参数:规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推。
// 第二个参数:规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。
{
  //元素是基本类型数据
  const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
  console.log(animals.slice(NaN)) // [ 'ant', 'bison', 'camel', 'duck', 'elephant' ]
  console.log(animals.slice('A')) // [ 'ant', 'bison', 'camel', 'duck', 'elephant' ]
  console.log(animals.slice('1')) // [ 'bison', 'camel', 'duck', 'elephant' ]
  console.log(animals.slice(2.1, 4.8)) // [ 'camel', 'duck', 'elephant' ]
  console.log(animals.slice(4, 2)) // [] 开头数字比结尾数字大,会返回空数组
  console.log(animals.slice(-2)) // ["duck", "elephant"]
  console.log(animals.slice(2, -2)) // ["camel"]
  console.log(animals.slice(2)) // ["camel", "duck", "elephant"]
  console.log(animals.slice(2, 4)) // ["camel", "duck"]
  console.log(animals.slice()) // ['ant', 'bison', 'camel', 'duck', 'elephant']

  //元素是引用类型数据
  let arr = [{
    a: 1
  }, {
    a: 2
  }]
  let newArr = arr.slice(0, 1)
  console.log(arr, newArr) //=> [ { a: 1 }, { a: 2 } ]        [ { a: 1 } ]

  newArr[0].a = 20
  console.log(arr, newArr) //=> [ { a: 20 }, { a: 2 } ]       [ { a: 20 } ]
}

//5. 数组合并
// concat
// 用于合并两个或多个数组,不会更改现有数组,会返回一个新的数组。
{
  const array1 = ['a', 'b', 'c', {
    name: 'boy'
  }]
  const array2 = ['d', 'e', 'f']
  const array3 = array1.concat(array2)
  array3[3].name = 'sex'
  console.log(array1) // [ 'a', 'b', 'c', { name: 'sex' } ]  使用slice和concat对对象数组的拷贝,整个拷贝还是浅拷贝,拷贝之后数组各个值的指针还是指向相同的存储地址。
  console.log(array3) // [ 'a', 'b', 'c', { name: 'sex' }, 'd', 'e', 'f' ]
}

//6. 拓展运算符
// 不会更改源数组,拓展运算符也可以把 Set 转为数组。
{
  let temp1 = [1, 2, 3]
  let temp2 = [4, 5, 6]
  let arr = [...temp1, ...temp2]
  console.log(arr) //[1,2,3,4,5,6]
}

// flat
// 多维数组合并,返回一个新的数组。 (浏览器支持性不好)

// {
//     // 合并一维数组
//     let ary = [1, 2, [3, 4], 5]
//     let newAry = ary.flat();
//     console.log(newAry) //=> [1,2,3,4,5]

//     //合并多维数组
//     [1, 2, [3, [4, [5, 6]]]].flat('Infinity'); //=> [1,2,3,4,5,6]

//     //移除数组空项
//     let arr = [1, 2, , 5];
//     let newArr = arr.flat();
//     // 原数组不会发生变化
//     console.log(arr, newArr); //=> [1, 2,, 5] [1, 2, 5]
// }

//7. 数组迭代(循环)

// forEach
// 遍历数组,对每个元素执行一次函数,不会更改源数组,也不会创建新数组。
// 第一个参数:当前元素
// 第二个参数:当前元素的索引值
// 第三个参数:当前元素所在的数组
{
  let temp = [1, 3, 5]
  temp.forEach(function (value, index, array) {
    console.log(value, index, array)
  })
  /****
    1 0 [1,3,5] 
    3 1 [1,3,5]
    5 2 [1,3,5]
    ***/
}

// map
//  map() 不会对空数组进行检测。(结果还是空数组)
// 遍历数组,对每个元素执行一次函数,不会更改源数组,会创建一个新数组。
// 函数中也可以传入三个参数,和foreach方法中的参数一致
{
  const array2 = []
  const array1 = [1, 4, 9, 16]
  const map1 = array1.map((x) => x * 2)
  const map2 = array2.map((x) => x * 2)
  console.log(map1) //=> [2, 8, 18, 32]
  console.log(map2) // []
}

// filter
// 遍历数组,对每个元素执行一次函数,返回满足规则的元素。
{
  const words = [
    'spray',
    'limit',
    'elite',
    'exuberant',
    'destruction',
    'present',
  ]
  const result = words.filter((word) => word.length > 6)
  console.log(result) //=> ["exuberant", "destruction", "present"]
}

// every
// 遍历数组,对每个元素执行一次函数,用于测试组内元素,是否全部满足指定规则。
// 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
{
  const isBelowThreshold = (currentValue) => currentValue < 40
  const array1 = [1, 30, 39, 29, 10, 13]
  console.log(array1.every(isBelowThreshold)) //=> true
}

// some
// 遍历数组,对每个元素执行一次函数,用于判断组内元素至少有一个元素通过了指定规则。
// 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
{
  const array = [1, 2, 3, 4, 5]
  const even = (element) => element % 2 === 0
  console.log(array.some(even)) //=> true
}

// reduce

// reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
// reduce() 可以作为一个高阶函数,用于函数的 compose。
// 注意: reduce() 对于空数组是不会执行回调函数的。
// reduce方法中的函数参数:第一个参数:初始值, 或者计算结束后的返回值。后面的参数依次是当前元素,当前元素的索引值和当前元素所在数组
{
  const array1 = [1, 2, 3, 4]
  const reducer = (accumulator, currentValue) => accumulator + currentValue
  // 1 + 2 + 3 + 4
  console.log(array1.reduce(reducer)) //=> 10
  // 这里的5表示传递给函数的初始值
  // 5 + 1 + 2 + 3 + 4
  console.log(array1.reduce(reducer, 5)) //=> 15
}

// for循环

// for...in循环
{
  const array1 = ['a', 'b', 'c']
  const obj1 = {
    name: 'ming',
    age: '18',
    sex: 'boy'
  }
  for (const element in array1) {
    console.log(element) //0,1,2
  }
  for (const elementObj in obj1) {
    console.log(elementObj) //name,age,boy
  }
}

// for...of循环
// for..of循环无法循环对象,因为能够被for...of正常遍历的,都需要实现一个遍历器Iterator。而数组、字符串、Set、Map结构,早就内置好了Iterator(迭代器),它们的原型中都有一个Symbol.iterator方法,而Object对象并没有实现这个接口,使得它无法被for...of遍历。
{
  const array1 = ['a', 'b', 'c']
  for (const element of array1) {
    console.log(element) //a,b,c
  }
}

//8. 查找定位

// indexOf
// 获取数组元素的索引。 对大小写敏感
// 字符串同样可以用这个方法
// 第二个参数表示检索的起始位置
{
  const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']
  console.log(beasts.indexOf('duck')) // 3
  console.log(beasts.indexOf('ant', 2)) // -1
  console.log(beasts.indexOf('gogo')) // -1  未找到,返回-1
}

// lastIndexOf
// 获取数组元素最后一个索引。
// 第二个参数表示检索的起始位置
{
  const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
  console.log(animals.lastIndexOf('Dodo')) // 3
  console.log(animals.lastIndexOf('Tiger', 2)) // 1
  console.log(animals.lastIndexOf('Apple')) // -1 未检索到返回-1
}

// findIndex
// 循环数组,返回第一个满足条件的索引。
// 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
// 如果没有符合条件的元素返回 -1
// 函数中参数和foreach一样,分别为,当前值,当前值的索引,当前值所在的数组
{
  const array1 = [5, 12, 8, 130, 44]
  const where = (value) => value > 13
  console.log(array1.findIndex(where)) // 3
}

// find
// 循环数组,返回第一个满足条件的元素值。
// 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
// 如果没有符合条件的元素返回 undefined
// 函数中参数和foreach一样,分别为,当前值,当前值的索引,当前值所在的数组
{
  const array1 = [5, 12, 8, 130, 44]
  const where = (value) => value > 13
  console.log(array1.find(where)) // 130
}
var arr = [
  [1, 2],
  ['a', 'b'],
]
console.log(arr[1][0]) //a 第2列第1行所在的元素
console.log(arr)

//9. 数组排序

// sort
// 数组排序,直接修改原数组,如果不带参数,默认按照数组元素的字母排序,如果是数字则按照大小顺序排列。
{
  let array1 = ['bi', 'ci', 'di', 'ai']
  console.log(array1.sort()) // ai bi ci di

  let array2 = [1, 2, 3, 4]
  array2.sort((a, b) => {
    //retrun a - b // 升序
    return b - a // 降序
  })
  console.log(array2) // [4,3,2,1]
}

// reverse
// 数组倒序,不更改源数组,返回一个新的数组。
{
  const array1 = ['one', 'two', 'three']
  const array2 = array1.reverse()
  console.log(array2) // ["three", "two", "one"]
}

//10. 数组转换

// toString
// 将数组元素转为字符串,并以逗号分割,不更改源数组
{
  const array1 = [1, 2, 'a', '1a']
  console.log(array1.toString()) // "1,2,a,1a"
}

// join
// 将数组所有元素连接成一个字符串返回,可以指定连接符。
{
  const elements = ['Fire', 'Air', 'Water']
  console.log(elements.join()) // Fire,Air,Water
  console.log(elements.join('-')) // Fire-Air-Water
}

//11. 填充/包含

// fill
// 用一个固定的值,替换掉数组中指定起始位置到结束位置的全部元素。
// 第一个参数: 填充的值。
// 第二个参数:填充的起始位置
// 第三个参数:填充的结束位置
{
  const array1 = [1, 2, 3, 4]
  console.log(array1.fill(0, 2, 4)) //  [ 1, 2, 0, 0 ]
  console.log(array1.fill(5, 1)) // [1, 5, 5, 5]
  console.log(array1.fill(6)) // [6, 6, 6, 6]
}

// includes
// 判断数组中是否包含一个指定的值。
{
  const array1 = [1, 2, 3]
  console.log(array1.includes(2)) //true
}

//12. 查找定位

// indexOf
// 获取数组元素的索引
// 没有找到返回-1
// 第二个参数表示开始检索的位置
{
  const beasts = [1, 'ant', 'bison', 'camel', 'duck', 'bison', 1]
  console.log(beasts.indexOf('duck')) // 4
  console.log(beasts.indexOf('gogo')) // -1
  console.log(beasts.indexOf(1)) // 0  有多个时,返回查找的第一个元素位置
}

// lastIndexOf
// 获取数组元素最后一个索引。从后往前查找,如果查找到多个,则返回第一次找到的元素下标
// 没有找到返回-1
// 第二个参数表示开始检索的位置
{
  const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
  console.log(animals.lastIndexOf('Dodo')) // 3
}

// findIndex
// 不改变原数组中的值
// 循环数组,返回第一个满足条件的索引。
// 函数中参数依次为:当前值,当前值索引,当前值所在数组
{
  const array1 = [5, 12, 8, 130, 44]
  const where = (value) => value > 13
  console.log(array1.findIndex(where)) // 3
}

// find
// 不改变原数组中的值
// 循环数组,返回第一个满足条件的元素值。
// 函数中参数依次为:当前值,当前值索引,当前值所在数组
{
  const array1 = [5, 12, 8, 130, 44]
  const where = (value) => value > 13
  console.log(array1.find(where)) // 130
}

//12. 数组排序

// sort
// 数组排序,直接修改原数组,如果不带参数,默认按照数组元素的字母排序,如果是数字则按照大小顺序排列。
{
  let array1 = ['bi', 'ci', 'di', 'ai']
  console.log(array1.sort()) // ai bi ci di

  let array2 = [1, 2, 3, 4]
  array2.sort((a, b) => {
    //retrun a - b // 生序
    return b - a // 降序
  })
  console.log(array2) // [4,3,2,1]
}

// reverse
// 数组倒序,不更改源数组,返回一个新的数组。
{
  const array1 = ['one', 'two', 'three']
  const array2 = array1.reverse()
  console.log(array2) // ["three", "two", "one"]
}

//13. 数组转换

// toString
// 将数组元素转为字符串,并以逗号分割,不更改源数组。
{
  const array1 = [1, 2, 'a', '1a']
  console.log(array1.toString()) // "1,2,a,1a"
}

// join
// 将数组所有元素连接成一个字符串返回,可以指定连接符
// 默认使用逗号作为分隔符
{
  const elements = ['Fire', 'Air', 'Water']
  console.log(elements.join()) // Fire,Air,Water
  console.log(elements.join('-')) // Fire-Air-Water
}

//14. 填充/包含

// fill
// 用一个固定的值,替换掉数组中指定起始位置到结束位置的全部元素。
// 三个参数分别为:填充的值,起始位置,结束位置
{
  const array1 = [1, 2, 3, 4]
  console.log(array1.fill(0, 2, 4)) //  [ 1, 2, 0, 0 ]
  console.log(array1.fill(5, 1)) // [1, 5, 5, 5]
  console.log(array1.fill(6)) // [6, 6, 6, 6]
}

// includes
// 判断数组中是否包含一个指定的值。
// 第二个参数为:查找的其实位置,若为复式则是从后往前找
{
  const array1 = [1, 2, 3]
  console.log(array1.includes(2)) //true
}

//15. Array 的类方法

// isArray
// 类型判断
{
  console.log(Array.isArray([1, 2, 3])) // true
  console.log(Array.isArray({
    num: 123
  })) // false
}

// from
// 字符串转数组
{
  Array.from('foo') // ['f','o','o']
}

// set转数组
{
  const set = new Set(['foo', 'bar', 'baz', 'foo'])
  Array.from(set) // [ "foo", "bar", "baz" ]
}

// map转数组
{
  const map = new Map([
    ['name', '666'],
    ['name', 'pp'],
  ])
  Array.from(map) // ['name','pp']
}

// 循环数组
{
  Array.from([1, 2, 3], (x) => x + x) // [2, 4, 6]
}


{
  let ary = [12, 13, 31, 9, 32];
  ary.sort((a, b) => {
    console.log(a, b)
  })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值