数组方法大全

2022-07-15  本文已影响0人  假笑boys
JavaScript 数组方法大全
会改变原数组的方法: unshift(); push(); shift(); pop(); sort(); reverse(); splice(); copyWithin(); fill();
\color{#FF8C00}{\rm\large{concat()}}
 var str1 = [12,22,34,'justin',100];
 var str2 = ['bieber']
 console.log(str1.concat(str2))  
 // [12, 22, 34, 'justin', 100, 'bieber']
 console.log(str1) 
 // [12, 22, 34, 'justin', 100]
let str3 = [...str1,...str2]

\color{#FF8C00}{\rm\large{join()}}
 var str1 = [12,22,'hello']
 var str2 = str1.join("-")
 console.log(str2)  // 12-22-hello
 console.log(str1)  // [12, 22, 'hello']
\color{#FF8C00}{\rm\large{pop()}}
 var str1 = [12,22,33,44,55]
 var str2 = str1.pop()
 console.log(str2)  // 55 
 console.log(str1)  // [12, 22, 33, 44]
\color{#FF8C00}{\rm\large{shift()}}
 var str1 = [12,2,"hello"];
 console.log(str1.shift());      //12
 console.log(str1);          //[2,"hello"]
\color{#FF8C00}{\rm\large{unshift()}}
 var str1 = [12,2,"hello"];
 var str2 = [43,2,"test"];
 console.log(str1.unshift("你好"));       //4
 console.log(str2.unshift("hello","world"));  //5
 console.log(str1);            // ["你好", 12, 2, "hello"]
 console.log(str2);           // ['hello', 'world', 43, 2, 'test']
\color{#FF8C00}{\rm\large{push()}}
 var str1 = [12,2,"hello"];
 var str2 = [43,2,"test"];
 console.log(str1.push("你好"));          //4
 console.log(str2.push("hello","world"));    //5
 console.log(str1);                 //[12, 2, "hello","你好"]
 co
 nsole.log(str2);                 //[43, 2, "test","hello", "world"]

\color{#FF8C00}{\rm\large{reverse()}}
 var str1 = [12,2,"hello"];
 console.log(str1.reverse());      //["hello", 2, 12]
 console.log(str1);            //["hello", 2, 12]

\color{#FF8C00}{\rm\large{sort()}}
 var str1 = [12,2,43,5,2,5];
 var str2 = [92,2,43,"hello",5,2,5,"abc","zoom"];
 console.log(str1.sort());        //[12, 2, 2, 43, 5, 5]
 console.log(str1);            //[12, 2, 2, 43, 5, 5]
 console.log(str2.sort());        //[2, 2, 43, 5, 5, 92, "abc", "hello", "zoom"]
 console.log(str2);            //[2, 2, 43, 5, 5, 92, "abc", "hello", "zoom"]
 let person =[
   {name:'第一',age:12},
   {name:'第二',age:23},
   {name:'第三',age:5}
 ]
 person.sort((a,b)=>{
   // 参数 a 减去 参数 b  返回的值是 升序排列 
   // 参数 b 减去 参数 a  返回的值是 降序排列
   return b.age-a.age
 })
console.log(person)
\color{#FF8C00}{\rm\large{slice()}}
 let arr = ['T1','T2','T3','T4','T5','T6']
 console.log(arr.slice(1,3))  // ['T2', 'T3'] 
 console.log(arr.slice(1))    // ['T2', 'T3', 'T4', 'T5', 'T6']
 // -4 表示 start 从末尾开始数 ,默认从1开始 end 到 1 那个位置但不含 -1 
 console.log(arr.slice(-4,-1)) // ['T3', 'T4', 'T5']
 console.log(arr.slice(-2))   // ['T5', 'T6']
 console.log(arr.slice(1,-2))  // ['T2', 'T3', 'T4']
 console.log(arr)  // ['T1', 'T2', 'T3', 'T4', 'T5', 'T6'] 不会改变原数组
\color{#FF8C00}{\rm\large{splice()}}
var list = [11,22,33,44,55,66]
console.log('原始数据',list)

// 删除
list.splice(0,2)     // 删除  -> 从下标为0开始,长度为1
console.log(list)   // [33, 44, 55, 66]
list.splice(0,2)    // 删除  -> 从下标为0开始,长度为2
console.log(list)   // [55, 66]

// 替换
list.splice(0,1,4)   // 替换 -> 从下标为0开始,长度为1的数组元素替换成4
console.log(list)    // [4, 22, 33, 44, 55, 66]
list.splice(0,3,4)   //  替换 -> 从下标为0开始,长度为2的数组元素替换成4(即4,2整体替换成4)
console.log(list)    // [4, 44, 55, 66]


// 添加
list.splice(2,0,5)  // 表示在下标为2处前添加一项5
console.log(list)  // [11, 22, 5, 33, 44, 55, 66]
\color{#FF8C00}{\rm\large{toString()}}
var str = [1,2,3];
console.log(str.toString());     //1,2,3
console.log(str);                //[1,2,3]

\color{#FF8C00}{\rm\large{valueOf()}}
var str = [1,2,3];
console.log(str.valueOf());         //[1,2,3]
console.log(str);                   //[1,2,3]
//为了证明返回的是数组自身
console.log(str.valueOf() == str);  //true

\color{#FF8C00}{\rm\large{IndexOf()}}
var str = ["h","e","l","l","o"];
console.log(str.indexOf("l"));        //2
console.log(str.indexOf("l",3));      //3
console.log(str.indexOf("l",4));      //-1
console.log(str.indexOf("l",-1));     //-1
console.log(str.indexOf("l",-3));     //2

\color{#FF8C00}{\rm\large{lastIndexOf()}}
var str = ["h","e","l","l","o"];
console.log(str.lastIndexOf("l"));        //3

\color{#FF8C00}{\rm\large{forEach()}}
 var arr = ["Tom","Jack","Lucy","Lily","May"];
 var a = arr.forEach(function(value,index,self){
     console.log(value + "--" + index + "--" + (arr === self));
 })

 // 打印结果为:
 // Tom--0--true
 // Jack--1--true
 // Lucy--2--true
 // Lily--3--true
 // May--4--true
 console.log(a);     //undefined---forEach没有返回值
\color{#FF8C00}{\rm\large{map()}}
  // set
  let newArrInfo = new Map()
  newArrInfo.set('first','第一')
  newArrInfo.set('two','第二')
  console.log('set赋值',newArrInfo)  //  {'first' => '第一', 'two' => '第二'}
  // get
  // 该方法返回key对应的value,如果不存在,则返回undefined。
  let getArrInfo = newArrInfo.get('first')
  console.log('get获取值',getArrInfo)   // 第一
  // has 
  // 方法用于检查Map是否有指定key对应的value。  
  console.log(newArrInfo.has('justin'))  // false
  // clear
  该方法用于清空指定map对象中的所有内容
  console.log(newArrInfo.size)
  newArrInfo.clear()
  console.log(newArrInfo.size)
  // delete 
  该方法用于删除map中指定key对应的一组key-value元素 
  console.log(newArrInfo.delete('first'))
  console.log(newArrInfo)
  // Map 遍历方式对比
  let newCity = new Map();
  newCity.set('shanghai','上海')
  newCity.set('beijing','北京')
  newCity.set('guangzhou','广州')
  console.log(newCity)
  // 使用keys()方法
  console.log(newCity.keys())
  // 遍历 key
  for(let key of newCity.keys()){
    console.log(key)
  }
  // values() 同key 使用方法一样
  console.log(newCity.entries()) // {'shanghai' => '上海', 'beijing' => '北京', 'guangzhou' => '广州'}
  for( let [key,value] of newCity.entries()){
    console.log(key,value)  // shanghai 上海 beijing 北京 guangzhou 广州
  }
\color{#FF8C00}{\rm\large{filter()}}
 //功能1:同forEach
 var arr = ["Tom","Jack","Lucy","Lily","May"];
 var a = arr.filter(function(value,index,self){
     console.log(value + "--" + index + "--" + (arr === self))
 })
 // 打印结果为:
 // Tom--0--true
 // Jack--1--true
 // Lucy--2--true
 // Lily--3--true
 // May--4--true

 //功能2:当回调函数的返回值为true时,本次的数组值返回给filter,被filter组成新数组返回
 var arr = ["Tom","Jack","Lucy","Lily","May"];
 var a = arr.filter(function(value,index,self){
     return value.length > 3;
 })
 console.log(a);         //["Jack", "Lucy", "Lily"]
 console.log(arr);       //["Tom", "Jack", "Lucy", "Lily", "May"]---原数组未改变

\color{#FF8C00}{\rm\large{every()}}
//demo1:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
    console.log(value + "--" + index + "--" + (arr == self))
})
// 打印结果为:
// Tom--0--true
//因为回调函数中没有return true,默认返回undefined,等同于返回false

//demo2:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
    console.log(value + "--" + index + "--" + (arr == self))
    return value.length < 4;
})
// 打印结果为:
// Tom--0--true
// abc--1--true
// Jack--2--true
//因为当遍历到Jack时,回调函数到return返回false,此时Jack已经遍历,但是后面数据就不再被遍历了

//demo3:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
    console.log(value + "--" + index + "--" + (arr == self))
    return true;
})
// 打印结果为:
// Tom--0--true
// abc--1--true
// Jack--2--true
// Lucy--3--true
// Lily--4--true
// May--5--true
//因为每个回调函数的返回值都是true,那么会遍历数组所有数据,等同于forEach功能

\color{#FF8C00}{\rm\large{some()}}
 //demo1:
   var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
   var a = arr.some(function(value,index,self){
       console.log(value + "--" + index + "--" + (arr == self))
       return value.length > 3;
   })
   // 打印结果为:
   // Tom--0--true
   // abc--1--true
   // Jack--2--true

\color{#FF8C00}{\rm\large{Array.from()}}
 let str = '12345'
 console.log(Array.from(str))    // ["1", "2", "3", "4", "5"]
 let obj = {0:'a',1:'b',length:2}
 console.log(Array.from(obj))   // ["a", "b"]
 let aa= {0:'a',1:'b'}
 console.log(Array.from(aa))   // []
\color{#FF8C00}{\rm\large{Array.of()}}
 let str = '11'
 console.log(Array.of(str))   // ['11']
 // 等价于
 console.log(new Array('11'))  // ['11]
\color{#FF8C00}{\rm\large{arr.find(callback)}}
let arr = [1,2,3,4,5,2,4]
let arr1 = arr.find((value, index, array) =>value > 2)
console.log(arr1)   // 3 表示的是 值
\color{#FF8C00}{\rm\large{arr.findIndex(callback)}}
let arr = [1,2,3,4,5]
let arr1 = arr.findIndex((value, index, array) => value > 3)
console.log(arr1)  // 3
\color{#FF8C00}{\rm\large{arr.includes()}}
 let arr = [1,2,3,4,5]
 let arr1 = arr.includes(2)  
 console.log(arr1)   // ture
 let arr2 = arr.includes(9) 
 console.log(arr2)    // false
 let arr3 = [1,2,3,NaN].includes(NaN)
 console.log(arr3)  // true

\color{#FF8C00}{\rm\large{reduce}}
 //数组求和
 var arr = [{money:12},{money:22},{money:32},{money:42},{money:52}]
 var sum = arr.reduce(function(total,currentValue){
   return total+currentValue.money
 },0)
 console.log(sum)
 // 合并二维数组
 var info = [['mu','zi'],['dig','pig'],['luck','infos'],['justin','bieber']]
 var newInfo = info.reduce(function(total,currentValue){
   return total.concat(currentValue) 
 })
 console.log(newInfo) // ['mu', 'zi', 'dig', 'pig', 'luck', 'infos', 'justin', 'bieber']
 // 统计一个数组中有多少哥不重复的单词
 
 // 不用reduce时: 
 var arr = ["apple","orange","apple","orange","pear","orange"]; 
 function getWordCnt(){ 
   var obj = {}; 
   for(var i= 0, l = arr.length; i< l; i++){ 
     var item = arr[i]; 
     obj[item] = (obj[item] +1 ) || 1; 
   } 
   return obj; 
 }
 console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}
 // 用reduce时: 
 var arr = ["apple","orange","apple","orange","pear","orange"]; 
 function getWordCnt(){ 
   return arr.reduce(function(prev,next){ 
     prev[next] = (prev[next] + 1) || 1; 
     return prev; 
   },{}); 
 } 
 console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}
上一篇下一篇

猜你喜欢

热点阅读