面试题

144 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情

1. js延迟加载

会背

  • defer:等html全部加载完成,才会顺次执行js代码。
  • async:和html解析是同步的,不是顺次执行js代码,谁先加载完先执行谁。

理解

如下引入外部js文件script.js,在script.js中打印了对应id是root的元素。但是因为我们在head标签中先引入的外部文件,然后才去渲染的dom,所以此时结果为 null。

<html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <div id="root">sdsdassa</div>
</body>
</html>

script.js

console.log(document.getElementById('root'))

此时在,script标签中添加async或者defer,这就是延迟加载

 <script src="script.js" async></script>
  • <script>

image.png

  • <script async>

image.png

  • <script defer> image.png

2. 数据类型

  • 基本数据
string number boolean undefined null symbol bigint
  • 引用类型
object(array function)

考题

  • 字符串和其他类型相加就会变成字符串。
  • NaN是一个数值类型,但是不是一个具体的数字
alert(true+1)    // 2
alert('name'+true) // 'nametrue'
alert(undefined+1)  // NaN    
typeof(undefined+1) // number
typeof(null)       // Object
typeof(undefined)  // undefined

使用加运算符的规律

  • 字符串和任何值相加,都变成字符串拼接。
  • 对于数值
    • 与非字符串类型相加,都将其转为数值
    • 只要存在NaN,结果就是NaN
    • Infinity + Infinity = Infinity
    • -Infinity + ( -Infinity) = -Infinity
    • -Infinity + Infinity = NaN
  • 对于运用数据类型,将会转为基本数据类型。转换时使用对象上的valueOf()或者toString()。具体使用哪个方法与调度机制有关。
// 对两个方法重写
const foo ={
    toString(){
        return 'toString'
    }
    valueOf(){
        return 1
    }
}
alert(foo)    // 隐式转换为'toString' 使用了toString
console.log(1+foo)  // 2 使用了 valueOf
nullundefined的区别
先有null 后有 undefinednull会被隐式的转换为0,并且是一个对象,很难发现错误。
undefined是为了填补之前的坑。

具体区别:
null是一个表示‘无’的对象(空对象指针),转为数值是0.
undefined是一个表示“无”的原始值/基本数据类型,转为数值是NaN

3. == 和 ===

  • == :比较的是值
  • === :除了比较值,还比较了类型