JS数组

2020-03-12  本文已影响0人  zhenghongmo

Array用法

基本用法

  1. Array(3)//{length:3} ,3表示length
  1. Array(3,3) // [3,3] ,第一个3并不表示length了
  1. 构造函数

Js中数组的本质

数组的API

  1. Array.prototype.forEach

forEach() 方法对数组的每个元素执行一次提供的函数。返回值为undefined

forEach()参数必须为一个函数

函数必须有三个参数,一个为数组当前项的值(value),一个为数组当前项的索引(key),一个为数组对象本身

  1. Array.prototype.sort

sort() 方法对数组的元素进行排序,并返回数组。默认排序顺序是根据字符串Unicode码点。

<font color="red">sort()是这几个方法中唯一会改变原数组的方法</font>

sort()有一个函数作为参数,这是用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。

  1. Array.prototype.join

join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。

  1. Array.prototype.concat

concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组.

  1. Array.prototype.toString

toString() 返回一个字符串,表示指定的数组及其元素。Array对象覆盖了Object的 toString 方法。对于数组对象,toString 方法连接数组并返回一个字符串,其中包含用逗号分隔的每个数组元素。

  1. Array.prototype.map

map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果

  1. Array.prototype.filter

filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

  1. Array.prototype.reduce

reduce() 方法对累计器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值。

  1. Array.prototype.push/Array.prototype.unshift()
  1. Array.prototype.pop/Array.prototype.shift()
  1. Array.prototype.includes()
  1. Array.prototype.indexOf()
  1. Array.prototype.lastIndexOf()
  1. Array.prototype.find()
  1. Array.prototype.findIndex()
  1. Array.prototype.some()
  1. Array.prototype.every()
  1. Array.prototype.slice()
  1. Array.prototype.splice()

合并两个数组

1、concat、for 循环、扩展运算法、Array.prototype.push.apply

let temparr2 = temparr.concat([7,8])
console.log(temparr2)//[ 1, 2, 3, 4, 7, 8 ]
arr1.push.apply(arr1,arr2)
console.log(arr1) //[ 1, 2, 3, 4, 4, 5, 6, 7 ]
let temparr = [1,2,3,4];
temparr.push([6,7])
console.log(temparr)//[ 1, 2, 3, 4, [ 6, 7 ] ]

合并两个对象

Object.assign、扩展运算法、手写深浅拷贝

const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };

const obj = Object.assign( o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。
上一篇 下一篇

猜你喜欢

热点阅读