数组迭代方法汇总

2021-02-03  本文已影响0人  vivianXIa

之前就像总结的 但是看了一些资料 觉得内容很多就没有来整理,觉得脑子过一遍差不多。结果没记住 sad
查看数组的哪些方法可以直接console.dir(Array.prototype)

数组的迭代方法

let arr = [1,2,3,4,5,6]

 //不能 return 
arr.forEach((v,i,a)=>{
})
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);

function myFunction(value) {
  return value * 2;
}
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
var numbers = [45, 4, 9, 16, 25];
var someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(n => typeof n === "number")) // 0
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
let arr = [1, 2, 2, 4, null, null].reduce((accumulator, current) => {
    return accumulator.includes(current) ? accumulator : accumulator.concat(current);
}, []);

数组扁平化
数组求和
计算出现的次数

  let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

      let nameNum = names.reduce((pre,cur)=>{
        if(cur in pre){
          pre[cur]++
        }else{
          pre[cur] = 1 
        }
        return pre
      },{})
      console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

不同:
和reduce:从左向右边,reduceRight:从右边向左边

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}
let names = ['Tom','Jerry']
for(let i in names){
console.log(arr[i]);
}
//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.values()) {
  console.log(v)
}
//'a' 'b' 'c'

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.values()) {
  console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.values()) {
  console.log(v)
}
// 'a' 'b'

keys 返回键值对的 键值

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.keys()) {
  console.log(v)
}
// 0 1 2

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.keys()) {
  console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.keys()) {
  console.log(v)
}
// 'a' 'b'
var a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false
上一篇下一篇

猜你喜欢

热点阅读