常见的数组基本用法

1. 数组的构造器有哪几种?
//第一种:构造器方法new Array()

/*
 参数:
   a.new Array(arg1,arg2,...)参数长度为0或者长度大于等于2时,传入的参数将按照顺序依次成为新数组的第0至第N项。
   b.new Array(len) len不是Number类型时,返回只包含len元素一项的数组。
   c.new Array(len) len是Number时,返回数组长度为len的数组,最大不超过2的32次方(Math.pow(2,32))
*/
let arr1 = new Array(1,2,3)
console.log(arr1)//[1, 2, 3]
let arr2 = new Array(6)
console.log(arr2)//[empty × 6]
let arr3 = new Array('6')
console.log(arr3)//["6"]
//第二种:Array.of

/*
 Array.of方法基本和构造器方法一致,唯一区别是在一个参数时,Array.of依然返回数组元素为该值的一个数组。
*/
Array.of(8)//[8]
Array.of(8.0)//[8]
Array.of("8",8)// ["8", 8]
   //第三种:Array.from(类似从一个可迭代对象中创建一个新的数组实例)
   /*
     Array.from(arg1,arg2,arg3)
      第一个参数:类数组对象,可选
      第二个参数:加工函数,新生成的数组会经过该函数的加工再返回。
      第三个参数:this作用域,表示加工函数执行时的值。
   */
   const obj = {0:'a',1:'b',2:'c',length:3}
   let newArr = Array.from(obj,function(value,index){
     return value.repeat(3)
   },obj)
   console.log(newArr)// ["aaa", "bbb", "ccc"]
   
   //其他使用
   Array.from("abc") //["a", "b", "c"]
   Array.from(new Set(['abc','def']))// ["abc", "def"]
   Array.from(new Map([[1,'ab'],[2,'cd']]))//[[1, "ab"], [2, "cd"]]
2. 如何判断一个数组?方法有哪些?
const arr = []
//1.instanceof
arr instanceof Array
//2.constructor
arr.constructor === Array
//3.对象原型链Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(arr)
//4.getPrototypeOf
Object.getPrototypeOf(arr) === Array.prototype
//5.Object.prototype.toString
Object.prototype.toString(arr) === '[object Array]'
//6.Array.isArray()
Array.isArray(arr)
3. 哪些方法改变数组自身?

ES5方法:pop push  shift  unshift reverse sort splice

ES6方法:copyWithin fill

/*
 1.pop方法:
    定义:末尾删除元素,返回删除后的元素
       用法:arr.pop()
*/
    const array = ["cat", "dog", "cow", "chicken", "mouse"];
    let item = array.pop();
    console.log(array); // ["cat", "dog", "cow", "chicken"]
    console.log(item); // mouse

/*
 2.push方法:
    定义:末尾添加元素,返回添加元素后数组的长度。
    用法:arr.push(ele1,ele2,...)
*/
    const array = ["football", "basketball",  "badminton"];
    let i = array.push("golfball");
    console.log(array); //["football", "basketball", "badminton", "golfball"]
  console.log(i);//4
/*
 3.shift方法:
     定义:头部删除元素,返回被删除元素。如果数组为空返回undefined
     用法:arr.shift()
*/
    const array = [1,2,3,4,5];
    let item = array.shift();
    console.log(array); // [2,3,4,5]
    console.log(item); // 1
/*
 4.unshift方法:
     定义:头部添加元素,返回添加元素后,数组的长度。
     用法:arr.unshift(element1, ..., elementN)
*/
  const array = ["red", "green", "blue"];
    let length = array.unshift("yellow");
    console.log(array); // ["yellow", "red", "green", "blue"]
    console.log(length); // 4
/*
 5.reverse方法:
     定义:对数组元素进行翻转,返回翻转后的数组,该数组和原数组完全相等。
     用法:arr.reverse()
*/
    const array = [1,2,3,4,5];
    let array2 = array.reverse();
    console.log(array); // [5,4,3,2,1]
    console.log(array2===array); // true
/*
 6.sort方法:
     定义:对数组进行排序,返回排序后的数组,数组元素为数字,则正序排列;数组元素为字母,则按首字母ASCII码进行正序排列;数组元素为汉字,则按Unicode进行排序。
     用法:arr.sort(function(a,b){}) a和b分别为用于比较的元素
*/
 const array = ["apple","Boy","Cat","dog"];
  let array2 = array.sort();
  console.log(array); // ["Boy", "Cat", "apple", "dog"]
  console.log(array2 == array); // true
 //其他妙用
 const array1 = [6,10,2,5,4,8]
 let arr1 = array1.sort((a,b)=> a - b)//升序排列
 console.log(arr1)//[2, 4, 5, 6, 8, 10]
  let arr2 = array2.sort((a,b)=> b - a)//降序排列
 console.log(arr2)//[10, 8, 6, 5, 4, 2]
/*
 7.splice方法:
     定义:删除、替换现有元素或者添加新元素,并返回删除或修改后的数组。  
     用法:arr.splice(start,deleteCount,item1,....item n)
     参数:start是要修改的开始位置;deleteCount要删除的元素的个数;item为新添加的元素。
*/
 const array = ["apple","orange","banana","watermelon"];
 //删除元素
  let splices = array.splice(1,1);//从下标为1的开始,删除1个元素
  console.log(array); // ["apple", "banana", "watermelon"]
  console.log(splices); // ["orange"]
 //替换元素
 let replace = array.splice(1,1,'peach')
  console.log(array)//["apple", "peach", "banana", "watermelon"]
  console.log(replace)//["orange"]
 //增加元素
 let addItems = array.splice(1,0,'peach','pear')
  console.log(array)//["apple", "peach", "pear", "orange", "banana", "watermelon"]
 console.log(addItems)//[]
/*
 8.copyWithin方法:
     定义:从数组的指定位置拷贝元素到数组的另一个指定位置,返回辅助后的数组,不会改变原数组的长度。
     用法:arr.copyWithin(target,start,end)
     参数:target为复制元素存放的位置,如果是负数,target将从末尾开始计算。target大于数组长度则不会发生拷贝。
        start开始复制元素的起始位置,如果是负数,start从末尾开始计算。
        end开始复制元素的结束位置,不包含end这个位置的元素。
*/
  const array = [1,2,3,4,5]; 
  let arr = array.copyWithin(0,3);//从下标为3的位置开始复制其后的元素至数组的起始位置,将4和5复制到数组的头部
  console.log(arr);  // true [4, 5, 3, 4, 5]
 let arr1 = array.copyWithin(1,3,4)
  console.log(arr1)//[1, 4, 3, 4, 5]
/*
 9.fill方法:
    定义:把一个固定值替换为数组的元素,返回替换后的数组。
    用法:arr.fill(value,start,end)
    参数:value用来填充数组元素的值
        start起始索引
        end结束索引,默认值数组长度,不包含end索引。     
*/
  const array = [1,2,3,4,5];
  let arr = array.fill(10,0,3);//将数组0,1,2位置的元素替换为10
  console.log(arr);//true [10, 10, 10, 4, 5], 可见数组区间[0,3]的元素全部替换为10
4. 哪些方法不改变自身?

ES5:concat join slice toString toLocateString indexOf lastIndexOf

ES7:includes

/*
  1.concat方法:
       定义:合并数组,返回合并后的新数组(哪个数组调用concat方法,那个数组的元素在合并后在数组头部)。
       用法:let newArr = oldArr.concat(arr1,arr2,...)
       参数:参数为被合并的数组。
*/
const array = [1, 2, 3];
let array2 = array.concat(4,[5,6],[7,8,9]);
console.log(array2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array); // [1, 2, 3], 可见原数组并未被修改
/*
  2.join方法:
     定义:把数组中的所有元素转换成一个字符串,默认以逗号拼接。
     用法:arr.join(separator)
     参数:separator为分隔符
*/
const array = ['I', 'love', 'you'];
console.log(array.join()); // ""I,love,you""
console.log(array.join(' ')); // "I love you"
/*
 3.slice方法:
    定义:从已有数组中返回选定的元素(从start到end区间的元素,不包含end)。
    用法:arr.slice(start,end)
    参数:start和end分别为起始和结束索引,start默认为0,不包含end位置的元素。
         start超出数组索引范围,则返回空数组;start为负数,则从数组倒数第几个元素开始。
         end超数数组索引范围,默认截取到末尾;end为负数,则从数组倒数第几个元素开始。
*/
const array = ["one", "two", "three","four", "five"];
console.log(array.slice()); // ["one", "two", "three","four", "five"]
console.log(array.slice(2,3)); // ["three"]
console.log(array.slice(-2,-1))//["four"]
/*
 4.toString方法:
       定义:转换成字符,返回转换后的字符串,数组元素直接用逗号拼接。
       用法:arr.toString()
*/
const array = ['Jan', 'Feb', 'Mar', 'Apr'];
let str = array.toString();
console.log(str); // Jan,Feb,Mar,Apr
/*
  5.toLocaleString方法:
     定义:把数组的元素拼接成一个元素,数组中的元素各自使用toLocaleString方法转换成字符串,默认逗号隔开。
     用法:arr.toLocaleString(locales,options)
     参数:locales带有标记的字符串或字符串数组
          options可配置对象(Object,Number,Date)。
*/
const array = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);//1,a,12/21/1997, 2:12:00 PM
/*
  6.indexOf方法:
     定义:返回在数组中可以找到一个给定元素的【第一个索引】,如果不存在,返回-1。
     用法:arr.indexOf(searchElement,fromIndex)
     参数:searchElement要查找的元素
        fromIndex开始查找的位置
*/
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));// 1
  console.log(beasts.indexOf('bison',2));//4
/*
  7.lastIndexOf方法:
     定义:返回指定元素在数组中的【最后一个索引】,如果不存在返回-1。
     用法:arr.lastIndexOf(searchElement,fromIndex)
     参数:searchElement要查找的元素
        fromIndex开始查找的逆向位置,默认为数组长度减1。
*/
const animals = ['Pig', 'Tiger', 'Dog', 'Pig'];
console.log(animals.lastIndexOf('Pig'));// 3
console.log(animals.lastIndexOf('Pig',2))//0
/*
  8.includes方法:
     定义:用来判断一个数组是否包含一个指定的值,如果有返回true,否则返回false。(比较字符串时区分大小写)
     用法:arr.includes(item,fromIndex)
     参数:item需要查找的元素的值(字符串区分大小写)
        fromIndex开始查找索引位置  
*/
const numbers = [1,2,3,2]
console.log(numbers.includes(2))//true
console.log(numbers.includes(3,-1))//false
5. 遍历的方法有哪些?

ES5:forEach every some filter map reduce reduceRight

ES6:entries find findIndex keys values

/*
  1.forEach方法:
      定义:对数组的每个元素执行一个给定的函数,返回值undefined。不能终止循环,除非抛出异常。
      用法:arr.forEach(function(currentValue,index,array){})
      参数:currentValue正在处理的元素
         index正在处理的元素的索引
         array正在操作的数组
*/
const arr = ['a','b','c','d']
const newArr = []
let resp = arr.forEach((ele,idx)=>{
  newArr[idx] = ele.toUpperCase()
})
console.log(newArr)//["A", "B", "C", "D"]
console.log(resp)//undefined
/*
  2.every方法:
       定义:测试数组内的所有元素是否都能通过某个指定的函数。返回Boolean。如果一个元素返回false,则立即返回false,不在继续执行。(若为空数组,直接返回true)
       用法:arr.every(function(element,index,array){})
       参数:element用于测试的元素
             index用于测试的元素的索引
             array调用every的当前数组
*/
const arr = [2,4,6,8,10]
let resp = arr.every((ele,idx)=>{
  return ele % 2 === 0
})
console.log(resp)//true

const arr1 = [2,4,6,9,10]
let resp1 = arr1.every((ele,idx)=>{
 console.log(idx)//0,1,2,3 未打印4
  return ele % 2 === 0
})
console.log(resp1)//false
/*
  3.some方法:
     定义:测试数组中是不是至少有一个元素通过了指定函数,返回Boolean。如有满足条件的值,立即返回(若为空数组,直接返回false)
     用法:arr.some(function(element,index,array){})
     参数:element正在处理的元素
        index正在处理的元素的索引
        array调用some的数组
*/
const arr = [1,2,3,4,5]
let resp = arr.some((ele,idx)=>{
  console.log(idx)//0,1,2  有满足条件的值,立即返回
  return ele >= 3
})
console.log(resp)//true
/*
  4.filter方法:
      定义:测试数组中的所有元素是否通过了指定函数,返回一个新数组。如果没有任何元素通过,则返回空数组。
      用法:arr.filter(function(element,index.array){})
      参数:element正在处理的元素
         index正在处理的元素的索引
         array调用filter的数组
*/

const words = ['spray', 'limit', 'elite',  'destruction', 'present'];
const result = words.filter((ele,idx)=>{
  return  ele.length > 6
});
console.log(result);//["destruction", "present"]
/*
  5.map方法:
     定义:为数组的每一个元素都执行一次指定的函数,返回一个新数组。
     用法:arr.map(function(element,index,array){})
     参数:element正在处理的元素
        index正在处理的元素的索引
        array调用filter的数组
*/
const sqrts = [9,16,25]
const nums = sqrts.map((ele,idx)=>{
  return Math.sqrt(ele)
})
console.log(nums)// [3, 4, 5]
/*
 6.reduce方法:
   定义:为数组中的每一个元素都执行指定函数,将其汇总的结果单个返回(从左往右)。
   用法:arr.reduce(function(accumulator, currentValue, index, array), initialValue])
      第一个参数:回调函数,四个参数,分别为:回调返回的初始值(如果没有初始值,则为数组第一个元素的值),数组中正在处理的元素,正在处理的元素的索引,调用reduce的原数组。
      第二个参数:为回调返回值的初始值。
*/
//基础用法:
const arr = [0, 1, 2, 3, 4]
let result = arr.reduce((prev, current,idx) =>{
  console.log(prev, current,idx)//0 1 1  1 2 2  3 3 3  6 4 4
 //初始值默认为数组第一个元素,索引则会从1开始,不是第0 。 
  return  prev +  current
});//无初始值
console.log(result)//10

let result1 = arr.reduce((prev, current,idx) =>{
  console.log(prev, current,idx)//10 0 0  10 1 1  11 2 2  13 3 3  16 4 4 
  return  prev +  current
},10);//初始值为10
console.log(result1)//20


//进阶用法:
//a.二位数组转一维数组
const arr = [[0, 1], [3, 2], [4, 5]]
let result = arr.reduce((prev,current,idx)=>{
  return prev.concat(current)
},[])
console.log(result)//[0, 1, 3, 2, 4, 5]
//b.计算数组中每个元素出现的次数
const names = ['Alice','Bob','Tiff','Bruce','Alice','Tom']
let result = names.reduce((allNames,name)=>{
  if(name in allNames){
     allNames[name]++
  }else{
     allNames[name] = 1
  }
  return allNames
},{})
console.log(result)//{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1, Tom: 1}
//c.根据属性对object进行分类
const peoples = [
  { name: 'Alice', age: 20 },
  { name: 'Max', age: 30 },
  { name: 'Max', age: 40 },
  { name: 'Tom', age: 50}
];
let groupByProperty = (arrs,property)=>{
    return arrs.reduce((acc,current)=>{
      let key = current[property]
      if(!acc[key]){
        acc[key] = []
      }
       acc[key].push(current)
      return acc
  },{})
}
let result = groupByProperty(peoples,'name')
console.log(result)//{"Alice":[{"name":"Alice","age":20}],"Max":[{"name":"Max","age":30},{"name":"Max","age":40}],"Tom":[{"name":"Tom","age":50}]}
/*
 7.reduceRight方法:
   定义:为数组中的每一个元素都执行指定函数,将其汇总的结果单个返回(从右往左)。
   用法:arr.reduce(function(accumulator, currentValue, index, array), initialValue])
      第一个参数:回调函数,四个参数,分别为:回调返回的初始值(如果没有初始值,则为数组最后一个元素的值),数组中正在处理的元素,正在处理的元素的索引,调用reduce的原数组。
      第二个参数:为回调返回值的初始值。
*/
const arr = [[0, 1], [3, 2], [4, 5]]
let result = arr.reduceRight((prev,current,idx)=>{
  return prev.concat(current)
},[])
console.log(result)//[4, 5, 3, 2, 0, 1]
/*
 8.find方法:
    定义:返回满足条件的第一个元素的值,否则返回undefined。
    用法:arr.find((ele,idx,array))
*/
const arr = [5, 12, 8, 130, 44];
const result = arr.find((ele,idx,array)=>{
  console.log(idx) //0 1
  return ele > 10
});
console.log(result);//12
/*
 9.findIndex方法:
    定义:返回满足条件的第一个元素的索引,没找到返回-1。
    用法:arr.findIndex((ele,idx,array))
*/
const arr = [5, 12, 8, 130, 44];
const idx = arr.findIndex((ele,idx,array)=>{
  console.log(idx) //0 1
  return ele > 10
});
console.log(idx);//1
/*
 10.entries方法:
   定义:返回一个新的Array Iterator对象,包含[key,value]键值对。有一个next方法。
   用法:arr.entries()
*/
const arr = ['1','2','3','4','5']
let iterator = arr.entries()
console.log(iterator)//Array Iterator {}
console.log(iterator.next())//{"value": [0,"1"],"done": false}
//next.done 用于指示迭代器是否完成:在每次迭代时进行更新而且都是false,直到迭代器结束done才是true。
//拓展
for(let e of iterator){
  //循环之前不要调用next方法哦,不然迭代器会从最后一次开始执行。
  console.log(e)//[0, "1"] [1, "2"] [2, "3"] [3, "4"] [4, "5"] 
}
/*
 11.keys方法:
   定义:返回一个包含数组键的Array Iterator对象。
   用法:arr.keys()
*/
const arr = ['a', 'b', 'c']
const iterator = arr.keys();
for (const key of iterator) {
  console.log(key); //0 1 2
}
/*
 12.values方法:
   定义:返回一个包含数组每个索引值的Array Iterator对象。
   用法:arr.values()
*/
const arr = ['a', 'b', 'c']
const iterator = arr.values();
for (const value of iterator) {
  console.log(value);//a b c
}

方法返回值是否改变原数组指定函数是否需要return遍历元素个数
forEachundefined所有元素
everytrue/false所有元素
sometrue/false满足条件
filter新数组所有元素
map新数组所有元素
reduce单个返回值所有元素
reduceRight单个返回值所有元素
find满足条件第一个元素满足条件
findIndex满足条件第一个元素的索引满足条件

6. 其他数组方法

数组扁平化:flat flatMap

/*
  1.flat方法:
    定义:按照指定深度递归遍历数组,并将所有元素合并到一个新数组返回。
       用法:arr.flat(depth)
       参数:depth为深度,默认为1。
 */
const arr = [1, 2, [3, 4, [5, 6]]];
let flat = arr.flat(Infinity)
console.log(flat)//[1, 2, 3, 4, 5, 6]
/*
  2.flatMap方法:
    定义:使用指定函数映射每个元素,返回压缩后的新数组。该方法效果等同于flat深度为1。
       用法:arr.flatMap(function(currentValue,index,array))
       参数:指定回调函数
 */
const arr = [[2], [4], [6], [8]]
let str = arr.flatMap((currentValue)=>{
  return currentValue
})
console.log(str)// [2, 4, 6, 8]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值