作为一个优秀前端工程师,必须知道的一些知识点

84 阅读1分钟

1.根据函数判断变量的数据类型

在这里的话推荐两种方法 a.可以根据typeof运算符,来看返回类型,但是typeof只能用来判断简单(值)类型的不能用来判断引用类型

let a = 8
let b = '8'
let c = true
let d = [1,2,3,4,5]
let e ={id:1,name:'15'}
let f =undefined

console.log(typeof a) //number
console.log(typeof b) //string
console.log(typeof c) //boolean
console.log(typeof d) //object
console.log(typeof e) //object
console.log(typeof f) //undefined

b.可以通过object原型链(prototype)上的tostring来判断变量的类型是最直接靠谱的这也是各大框架底层用来判断数据类型的方法

let a  = 8
let b = '8'
let c = true
let d = [1,2,3,4,5]
let e ={id:1,name:'15'}
let f =undefined

  myTypeof(a)//number
  myTypeof(b)//string
  myTypeof(c)//boolean4
  myTypeof(d)//Array
  myTypeof(e)//object
  myTypeof(f)//undefined
  function myTypeof(obj){
    console.log(Object.prototype.toString.call(obj))
  }

2.用reduce来统计字符出现频率

const str = 'aabbbadddccc1122334'
       const i = str.split('').reduce((ddd, char) => {
      char in ddd ? ddd[char]++ : ddd[char] = 1
      return ddd
      }, {})
      console.log(i)
      打印结果:{1: 2, 2: 2, 3: 2, 4: 1, a: 3, b: 3, d: 3, c: 3}

我们首先使用split('')将字符串拆分为字符数组 初始的累加器(ddd)是一个空对象{}。在每次迭代中,我们检查当前字符是否已经存在于累加器对象中。如果存在,我们将对应的计数加 最后,reduce方法返回累加器对象,其中包含每个字符的出现频率