JavaScript 数组/对象/字符串的遍历

文章目录

  • JavaScript 数组/对象/字符串的遍历
    • 面试题
    • 对象的遍历方法
      • 总结
    • 数组的遍历方法
      • 总结
      • 手写方法
      • 手写数组去重和数组扁平化

JavaScript 数组/对象/字符串的遍历

面试题

  • for in、for of 区别,分别对对象和数组使用问结果
  • 讲一下数组的遍历方法,filter与map的使用场景,some,every的区别
  • map的操作原理
  • map和forEach的区别
  • 使用迭代器实现for-of
  • 手写数组去重
  • 手写数组扁平化
  • map和filter的区别
  • 数组的常用方法
  • 用reduce实现map

对象的遍历方法

总结

方法 描述 遍历不可枚举属性 遍历继承属性 遍历Symbol属性
Object.keys(obj)
Object.values(obj)
Object.entries(obj)
返回给定对象的自身可枚举属性组成的数组
数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致
× × ×
for-in 遍历对象的属性,包括原型链上的可枚举属性 × ×
Object.getOwnPropertyNames() 返回对象的自身属性的属性名,包括不可枚举属性 × ×
Object.getOwnPropertySymbols() 只获取对象的Symbol类型的键名 × ×
Reflect.ownKeys(obj) 获取对象的键值,包含不可迭代的key和symbol类型的key ×
  • Object.keys() = for in + Object.hasOwnProperty()
  • Reflect.ownKeys() = Object.getOwnPropertyNames() + Object.getOwnPropertySymbols()

数组的遍历方法

总结

方法 描述 语法 返回新数组 参数的函数需要return
forEach array.forEach(function(当前元素, 下标,遍历的数组){}) × ×
for-of for item of items
item是局部遍历,对item的修改不会影响原数组
× ×
map 将原数组映射为一个新数组 array.map(function(当前元素, 下标,遍历的数组){},参数1的this指向)
reduce 数组的归并方法,相当于数组的累加器,常用于条件统计 array.reduce(function(上一轮累加值,当前元素,下标,遍历的数组),初始值) ×
不改变数组,返回累计结果

为本轮累计值
filter 过滤掉数组中不符合的元素,指定数组中符合条件的元素放入新数组 array.filter(function(当前元素, 下标,遍历的数组){},this指向)
some some用于表示查找,只要数组里面某个元素符合条件,结果就返回true,否则false array.some(function(当前元素, 下标,遍历的数组){},this指向) ×
返回boolean
every every是需要数组中所有元素都满足条件才返回true array.every(function(当前元素, 下标,遍历的数组){},this指向) ×
不改变数组,返回boolean

map和forEach的区别

  • map返回新数组,forEach不返回新数组
  • forEach 是遍历 map 是映射
  • map是函数式编程理念,foreach是过程式编程理念

手写方法

reduce方法:当第二个值没有传的时候,第一次循环prev的值,默认为数组的第一项,而cur的值为数组的第二项,也就是第一次循环

map、reduce、filter方法

/*map方法*/
Array.prototype._map = function(fn,thisTo){
  let res = []; //返回一个新数组
  for(let i=0;i<this.length;i++){
    res[i] = fn.call(thisTo,this[i],i,this) //参数当前元素,元素下标,遍历的数组
  }
  return res;
}

/*reduce方法*/
Array.prototype._reduce = function(fn,initValue){
  initValue = initValue || this.splice(0,1)[0];//没有就取第一个值,返回值是一个数组并且修改了原数组
  let res = initValue;
  for(let i=0;i<this.length;i++){
   res =  fn(res,this[i],i,this)
  }
  return res;
}
//测试方法
let arr = [1,2,3,4]
let result = arr._reduce((res, cur) => {
  return res + cur
},3)
console.log(result) // 13

/*filter方法*/
Array.prototype._filter = function(fn,thisTo){
  let res = [];
  for(let i=0;i<this.length;i++){
    if(fn.call(thisTo,this[i],i,this)) res.push(this[i]);
  }
}

reduce实现map和filter方法

/*reduce实现map方法*/
Array.prototype._map = function(fn,thisTo)
{
return this.reduce( (prev,cur,index,arr)=>{
          prev.push(fn.call(thisTo,cur,index,arr))
          return prev;
        },[]); //[]存放结果集
}
let val = [1, 5, 6]._map(item => {
  return item+ 1
} )
console.log(val);  // [2, 6, 7]

/*reduce实现filter方法*/
Array.prototype._filter = function(fn,thisTo)
{

return this.reduce( (prev,cur,index,arr)=>{
          if(fn.call(thisTo,cur,index,arr))prev.push(cur);
          return prev;
        },[]); //[]存放结果集
}

let val = [1, 5, 6]._filter(item => item > 2)
console.log(val);  // [5, 6]

手写数组去重和数组扁平化

数组去重

  1. ES6语法 set
function unique(arr){
  return [...new Set(arr)]
}
  1. reduec方法
function unique(array){
 return array.reduce((accumulator,current)=>{
	return  accumulator.includes(current) ? accumulator : accumulator.concat(current);
 },[])
}
  1. 循环+容器
    思路: 遍历数组,将数组值保存成object对象的属性,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存。
function unique(array){
 let map = {};
 let res = [];
 for(let i = 0;i<array.length;i++){
  let cur  =array[i]
   if(!map[cur]) {
      res.push(cur);
      map[cur] = 1;
    }
 }
 return res;
}
console.log(unique([4,3,2,2,3,1]))

数组扁平化
将多维数组转换为一维数组
核心就是有数组则继续遍历

[1,[2,3,[4,5]]].flat(Infinity)
  1. 递归+循环
function flatten(arr) {
    let result = [];
    arr.forEach(item=>{
        //递归返回的是一个一维数组,所以使用concat进行连接,concat连接返回新数组
        if(Array.isArray(item))result = result.concat(flatten1(item));
        else  result = result.concat(item);
    })
    return result;
}
  1. reduce写法
function flat(arr){
	return arr.reduce((accumulator,item)=>{
		return accumulator.concat(Array.isArray(item)?flat(item):item); //concat只能拼接一层
	},[])
}
const arr = [1, [2, [3, 4]]];
console.log(flat(arr)); // [1, 2, 3, 4]

你可能感兴趣的:(JavaScript,javascript)