9道简单的JS面试选择题(this等)

前言

虽然因为时间原因估计年前来不及找实习了,但是通过面试题来搞清楚一些基本概念的方法,查漏补缺的手段,确实是非常有效的。今天就分享一套看过的简单选择题,都是JS的基础,东西其实不多,但是做对就有些难度了。

JS七种基本类型

这个问题大家看到可能会一蒙,JS基本类型有几种这个问题,其实一直是在变的,S6加了个Symbol,而今年ES10又新增加了一个bigInt,加上原来的基本类型undefined, null, number, string, boolean一共是七个。

var和let

变量提升还是相对基础的:

> const a = () => {console.log(b); var b= 2}
undefined
> a()
undefined
undefined
> const a = () => {console.log(b); let b= 2}
Thrown:
SyntaxError: Identifier 'a' has already been declared

setTimeout和var、let的混合使用

> for (var i=0; i<3;i++){setTimeout(()=>console.log(i), 0)}
Timeout {
  _idleTimeout: 1,
  _idlePrev: [TimersList],
  _idleNext: [Timeout],
  _idleStart: 152226,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(asyncId)]: 719,
  [Symbol(triggerId)]: 5
}
> 3
3
3
> for (let i=0; i<3;i++){setTimeout(()=>console.log(i), 0)}
Timeout {
  _idleTimeout: 1,
  _idlePrev: [TimersList],
  _idleNext: [Timeout],
  _idleStart: 209949,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(asyncId)]: 982,
  [Symbol(triggerId)]: 5
}
> 0
1
2

数据类型与声明类型

> let a = 6
undefined
> let b=new Number(6)
undefined
> let c=6
undefined
> console.log(a==b)
true
undefined
> console.log(a===b)
false
undefined
> console.log(b===c)
false

对象作为键

> const a ={}
undefined
> const b = {key:'b'}
undefined
> const c = {key:'c'}
undefined
> a[b]=123
123
> a[c]=456
456
> a[b]
456

对象作为键时,不管对象如何变化,作为键都会转化成字符串类型,也就是’[object Object]’,因此这里的a只有:

> a
{ '[object Object]': 456 }

JS数组

JS数组是有既定的空值的:

> a = [1,2]
[ 1, 2 ]
> a[4]=2
2
> a
[ 1, 2, <2 empty items>, 2 ]

i++和++i

这个不用多解释了,前者是返回原值,后者是返回加1后的值

this和call

首先关于this,这部分内容我好像没在博客中详细讲解过,首先我们要记住,this会默认指向最后调用它的那个对象。下面是两个典型的例子:

> var b = '2'
undefined
> function c() {var b ='3';console.log(this.b)}
undefined
> c()
2
> var a = '1'
undefined
> var b = {a:'2',fn:function(){console.log(this.a)}}
undefined
> b.fn()
2
undefined
> global.b.fn()
2
undefined
> global.fn()

有趣的是就算我们把b.fn赋值给了一个新的函数h,当我们去调用h()时,得到的仍然是全局的a值,这是因为h()调用的对象仍然是全局global,在浏览器中自然就是window。

而this指向改变的方式也有很多,如箭头函数,箭头函数的 this 始终指向函数定义时的 this,而非执行时。接着就是经典的apply, call, bind了。

接着我们看这个题目:

> let obj1 = {name:'1',print:function(){return ()=>console.log(this.name)}}
undefined
> let obj2 = {name:'2'}
undefined
> obj1.print()()
1
undefined
> obj1.print().call(obj2)
1
undefined
> obj1.print.call(obj2)()
2

Obeject.hasOwnProperty 和 Set.has

这个直接看案例:

> obj
{ '1': 'a', '2': 'c' }
> obj.hasOwnProperty('1')
true
> obj.hasOwnProperty(1)
true
> let r = new Set([1,2,3,4])
undefined
> r
Set { 1, 2, 3, 4 }
> r.has(1)
true
> r.has('1')
false
发布了346 篇原创文章 · 获赞 330 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43870742/article/details/103591234