JS 自测清单(三)

发表于:2023-03-15
字数统计:26.8k 字
阅读时长:1.1 小时
阅读量:148

转载自 javascript-questions(star 支持一波)


101. 输出什么?

const one = (false || {} || null)\nconst two = (null || false || \"\")\nconst three = ([] || 0 || true)\n\nconsole.log(one, two, three)
  • A: false null []
  • B: null \"\" true
  • C: {} \"\" []
  • D: null null true

答案

答案: C

使用||运算符,我们可以返回第一个真值。 如果所有值都是假值,则返回最后一个值。

(false || {} || null):空对象{}是一个真值。 这是第一个(也是唯一的)真值,它将被返回。one等于{}

(null || false ||“”):所有值都是假值。 这意味着返回传递的值\"\"two等于\"\"

([] || 0 ||“”):空数组[]是一个真值。 这是第一个返回的真值。 three等于[]

102. 依次输出什么?

const myPromise = () => Promise.resolve('I have resolved!')\n\nfunction firstFunction() {\n  myPromise().then(res => console.log(res))\n  console.log('second')\n}\n\nasync function secondFunction() {\n  console.log(await myPromise())\n  console.log('second')\n}\n\nfirstFunction()\nsecondFunction()
  • A: I have resolved!, second and I have resolved!, second
  • B: second, I have resolved! and second, I have resolved!
  • C: I have resolved!, second and second, I have resolved!
  • D: second, I have resolved! and I have resolved!, second

答案

答案: D

有了 promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被 resolved/rejected,并且执行栈为空时才使用这个值。

我们可以在async函数中通过.thenawait关键字获得该值。 尽管我们可以通过.thenawait获得 promise 的价值,但是它们的工作方式有所不同。

firstFunction中,当运行到myPromise方法时我们将其放在一边,即 promise 进入微任务队列,其他后面的代码(console.log('second'))照常运行,因此second被打印出,firstFunction方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,I have resolved被打印出。

secondFunction方法中,我们通过await关键字,暂停了后面代码的执行,直到异步函数的值被解析才开始后面代码的执行。这意味着,它会等着直到 myPromise 以值I have resolved被解决之后,下一行second才开始执行。

103. 输出什么?

const set = new Set()\n\nset.add(1)\nset.add(\"Lydia\")\nset.add({ name: \"Lydia\" })\n\nfor (let item of set) {\n  console.log(item + 2)\n}
  • A: 3, NaN, NaN
  • B: 3, 7, NaN
  • C: 3, Lydia2, [Object object]2
  • D: \"12\", Lydia2, [Object object]2

答案

答案: C

“+” 运算符不仅用于添加数值,还可以使用它来连接字符串。 每当 JavaScript 引擎发现一个或多个值不是数字时,就会将数字强制为字符串。

第一个是数字 1。 1 + 2 返回数字 3。

但是,第二个是字符串 “Lydia”。 “Lydia” 是一个字符串,2 是一个数字:2 被强制转换为字符串。 “Lydia” 和 “2” 被连接起来,产生字符串 “Lydia2”。

{name:“ Lydia”}是一个对象。 数字和对象都不是字符串,因此将二者都字符串化。 每当我们对常规对象进行字符串化时,它就会变成[Object object]。 与 “2” 串联的 “ [Object object]” 成为 “[Object object]2”。

104. 结果是什么?

Promise.resolve(5)
  • A: 5
  • B: Promise {<pending>: 5}
  • C: Promise {<fulfilled>: 5}
  • D: Error

答案

答案: C

我们可以将我们想要的任何类型的值传递Promise.resolve,无论是否promise。 该方法本身返回带有已解析值的Promise (<fulfilled>)。 如果您传递常规函数,它将是具有常规值的已解决promise。 如果你通过了 promise,它将是一个已经 resolved 的且带有传的值的 promise。

上述情况,我们传了数字 5,因此返回一个 resolved 状态的 promise,resolve 值为5

105. 输出什么?

function compareMembers(person1, person2 = person) {\n  if (person1 !== person2) {\n    console.log(\"Not the same!\")\n  } else {\n    console.log(\"They are the same!\")\n  }\n}\n\nconst person = { name: \"Lydia\" }\n\ncompareMembers(person)
  • A: Not the same!
  • B: They are the same!
  • C: ReferenceError
  • D: SyntaxError

答案

答案: B

对象通过引用传递。 当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。

我们将 “person2” 的默认值设置为 “person” 对象,并将 “person” 对象作为 “person1” 的值传递。

这意味着两个值都引用内存中的同一位置,因此它们是相等的。

运行 “ else” 语句中的代码块,并记录They are the same!

106. 输出什么?

const colorConfig = {\n  red: true,\n  blue: false,\n  green: true,\n  black: true,\n  yellow: false,\n}\n\nconst colors = [\"pink\", \"red\", \"blue\"]\n\nconsole.log(colorConfig.colors[1])
  • A: true
  • B: false
  • C: undefined
  • D: TypeError

答案

答案: D

在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(colorConfig.colors)代替括号表示法(colorConfig [“ colors”])。

使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript 尝试在 colorconfig 对象上找到名为 colors 的属性。 没有名为 “colors” 的属性,因此返回 “undefined”。

然后,我们尝试使用[1]访问第一个元素的值。 我们无法对未定义的值执行此操作,因此会抛出Cannot read property '1' of undefined

JavaScript 解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号[并一直进行下去,直到找到右方括号]。 只有这样,它才会评估该语句。 如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。

107. 输出什么?

console.log(\"❤️\" === \"❤️\");
  • A: true
  • B: false

答案

答案: A

在内部,表情符号是 unicode。 heat 表情符号的 unicode 是“ U + 2764 U + FE0F”。 对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回 true。

108. 哪些方法修改了原数组?(null)


109. 输出什么?(null)



110. 这个函数干了什么?

JSON.parse()
  • A: Parses JSON to a JavaScript value
  • B: Parses a JavaScript object to JSON
  • C: Parses any JavaScript value to JSON
  • D: Parses JSON to a JavaScript object only

答案

答案: A

使用JSON.parse()方法,我们可以将 JSON 字符串解析为 JavaScript 值。

// 将数字字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值:\nconst jsonNumber = JSON.stringify(4) // '4'\nJSON.parse(jsonNumber) // 4\n\n// 将数组值字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值:\nconst jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]'\nJSON.parse(jsonArray) // [1, 2, 3]\n\n// 将对象字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值:\nconst jsonArray = JSON.stringify({ name: \"Lydia\" }) // '{\"name\":\"Lydia\"}'\nJSON.parse(jsonArray) // { name: 'Lydia' }

111. 输出什么?

let name = 'Lydia'\n\nfunction getName() {\n  console.log(name)\n  let name = 'Sarah'\n}\n\ngetName()
  • A: Lydia
  • B: Sarah
  • C: undefined
  • D: ReferenceError

答案

答案: D

每个函数都有其自己的执行上下文。 getName函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量name。 上述情况,getName函数包含其自己的name变量:我们用let关键字和Sarah的值声明变量name

带有let关键字(和const)的变量被提升,但是与var不同,它不会被 初始化。 在我们声明(初始化)它们之前,无法访问它们。 这称为 “暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript 会抛出ReferenceError: Cannot access 'name' before initialization

如果我们不在getName函数中声明name变量,则 javascript 引擎会查看原型链。会找到其外部作用域有一个名为name的变量,其值为Lydia。 在这种情况下,它将打印Lydia

let name = 'Lydia'\n\nfunction getName() {\n  console.log(name)\n}\n\ngetName() // Lydia

112. 输出什么?

function* generatorOne() {\n  yield ['a', 'b', 'c'];\n}\n\nfunction* generatorTwo() {\n  yield* ['a', 'b', 'c'];\n}\n\nconst one = generatorOne()\nconst two = generatorTwo()\n\nconsole.log(one.next().value)\nconsole.log(two.next().value)
  • A: a and a
  • B: a and undefined
  • C: ['a', 'b', 'c'] and a
  • D: a and ['a', 'b', 'c']

答案

答案: C

通过 yield 关键字,我们在 Generator 函数里执行yield表达式。通过 yield* 关键字,我们可以在一个Generator 函数里面执行(yield表达式)另一个 Generator 函数,或可遍历的对象 (如数组).

在函数 generatorOne 中,我们通过 yield 关键字 yield 了一个完整的数组 ['a', 'b', 'c']。函数one通过next方法返回的对象的value 属性的值 (one.next().value) 等价于数组 ['a', 'b', 'c'].

console.log(one.next().value) // ['a', 'b', 'c']\nconsole.log(one.next().value) // undefined

在函数 generatorTwo 中,我们使用 yield* 关键字。就相当于函数two第一个yield的值,等价于在迭代器中第一个 yield 的值。数组['a', 'b', 'c']就是这个迭代器。第一个 yield 的值就是 a,所以我们第一次调用 two.next().value时,就返回a

console.log(two.next().value) // 'a'\nconsole.log(two.next().value) // 'b'\nconsole.log(two.next().value) // 'c'\nconsole.log(two.next().value) // undefined

113. 输出什么?

console.log(`${(x => x)('I love')} to program`)
  • A: I love to program
  • B: undefined to program
  • C: ${(x => x)('I love') to program
  • D: TypeError

答案

答案: A

带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 (x => x)('I love') 返回的值。我们向箭头函数 x => x 传递 'I love' 作为参数。x 等价于返回的 'I love'。这就是结果 I love to program

114. 将会发生什么?

let config = {\n  alert: setInterval(() => {\n    console.log('Alert!')\n  }, 1000)\n}\n\nconfig = null
  • A: setInterval 的回调不会被调用
  • B: setInterval 的回调被调用一次
  • C: setInterval 的回调仍然会被每秒钟调用
  • D: 我们从没调用过 config.alert(), config 为 null

答案

答案: C

一般情况下当我们将对象赋值为 null,那些对象会被进行 垃圾回收(garbage collected) 因为已经没有对这些对象的引用了。然而,setInterval的参数是一个箭头函数(所以上下文绑定到对象 config 了),回调函数仍然保留着对 config的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,setInterval 的回调每 1000ms (1s) 会被调用一次。

115. 哪一个方法会返回 'Hello world!' ?

const myMap = new Map()\nconst myFunc = () => 'greeting'\n\nmyMap.set(myFunc, 'Hello world!')\n\n//1\nmyMap.get('greeting')\n//2\nmyMap.get(myFunc)\n//3\nmyMap.get(() => 'greeting')
  • A: 1
  • B: 2
  • C: 2 and 3
  • D: All of them

答案

答案: B

当通过 set 方法添加一个键值对,一个传递给 set方法的参数将会是键名,第二个参数将会是值。在这个 case 里,键名为 函数 () => 'greeting',值为'Hello world'myMap 现在就是 { () => 'greeting' => 'Hello world!' }

1 是错的,因为键名不是 'greeting' 而是 () => 'greeting'

3 是错的,因为我们给get 方法传递了一个新的函数。对象受 引用 影响。函数也是对象,因此两个函数严格上并不等价,尽管他们相同:他们有两个不同的内存引用地址。

116. 输出什么?

const person = {\n  name: \"Lydia\",\n  age: 21\n}\n\nconst changeAge = (x = { ...person }) => x.age += 1\nconst changeAgeAndName = (x = { ...person }) => {\n  x.age += 1\n  x.name = \"Sarah\"\n}\n\nchangeAge(person)\nchangeAgeAndName()\n\nconsole.log(person)
  • A: {name: \"Sarah\", age: 22}
  • B: {name: \"Sarah\", age: 23}
  • C: {name: \"Lydia\", age: 22}
  • D: {name: \"Lydia\", age: 23}

答案

答案: C

函数 changeAge 和函数 changeAgeAndName 有着不同的参数,定义一个 新 生成的对象 { ...person }。这个对象有着所有 person 对象 中 k/v 值的副本。

首项,我们调用 changeAge 函数并传递 person 对象作为它的参数。这个函数对 age 属性进行加一操作。person 现在是 { name: \"Lydia\", age: 22 }

然后,我们调用函数 changeAgeAndName ,然而我们没有传递参数。取而代之,x 的值等价 new 生成的对象:{ ...person }。因为它是一个新生成的对象,它并不会对对象 person 造成任何副作用。person 仍然等价于 { name: \"Lydia\", age: 22 }

117. 下面那个选项将会返回 6?

function sumValues(x, y, z) {\n\treturn x + y + z;\n}
  • A: sumValues([...1, 2, 3])
  • B: sumValues([...[1, 2, 3]])
  • C: sumValues(...[1, 2, 3])
  • D: sumValues([1, 2, 3])

答案

答案: C

通过展开操作符 ...,我们可以 暂开 单个可迭代的元素。函数 sumValues function 接收三个参数: x, yz...[1, 2, 3] 的执行结果为 1, 2, 3,将会传递给函数 sumValues

118. 输出什么?(null)

123
  • F: Hello world!

答案

答案: C

String.raw函数是用来获取一个模板字符串的原始字符串的,它返回一个字符串,其中忽略了转义符(\\n,\\v,\\t等)。但反斜杠可能造成问题,因为你可能会遇到下面这种类似情况:

119. 输出什么?

const person = {\n\tfirstName: \"Lydia\",\n\tlastName: \"Hallie\",\n\tpet: {\n\t\tname: \"Mara\",\n\t\tbreed: \"Dutch Tulip Hound\"\n\t},\n\tgetFullName() {\n\t\treturn `${this.firstName} ${this.lastName}`;\n\t}\n};\n\nconsole.log(person.pet?.name);\nconsole.log(person.pet?.family?.name);\nconsole.log(person.getFullName?.());\nconsole.log(member.getLastName?.());
  • A: undefined undefined undefined undefined
  • B: Mara undefined Lydia Hallie ReferenceError
  • C: Mara null Lydia Hallie null
  • D: null ReferenceError null ReferenceError

答案

答案: B

通过 ES10 或 TS3.7+可选链操作符 ?.,我们不再需要显式检测更深层的嵌套值是否有效。如果我们尝试获取 undefinednull 的值 (nullish),表达将会短路并返回 undefined.

person.pet?.nameperson 有一个名为 pet 的属性: person.pet 不是 nullish。它有个名为 name 的属性,并返回字符串 Mara

person.pet?.family?.nameperson 有一个名为 pet 的属性: person.pet 不是 nullish. pet 并没有 一个名为 family 的属性,person.pet.family 是 nullish。表达式返回 undefined

person.getFullName?.()person 有一个名为 getFullName 的属性: person.getFullName() 不是 nullish 并可以被调用,返回字符串 Lydia Hallie

member.getLastName?.(): 变量member 不存在,因此会抛出错误ReferenceError

120. 输出什么?

const groceries = [\"banana\", \"apple\", \"peanuts\"];\n\nif (groceries.indexOf(\"banana\")) {\n\tconsole.log(\"We have to buy bananas!\");\n} else {\n\tconsole.log(`We don't have to buy bananas!`);\n}
  • A: We have to buy bananas!
  • B: We don't have to buy bananas
  • C: undefined
  • D: 1

答案

答案: B

我们传递了一个状态 groceries.indexOf(\"banana\") 给 if 条件语句。groceries.indexOf(\"banana\") 返回 0, 一个 falsy 的值。因为 if 条件语句的状态为 falsy,else 块区内的代码执行,并且 We don't have to buy bananas! 被输出。

121. 输出什么?

const config = {\n\tlanguages: [],\n\tset language(lang) {\n\t\treturn this.languages.push(lang);\n\t}\n};\n\nconsole.log(config.language);
  • A: function language(lang) { this.languages.push(lang }
  • B: 0
  • C: []
  • D: undefined

答案

答案: D

方法 language 是一个 setter。Setters 并不保存一个实际值,它们的使命在于 修改 属性。当调用方法 setter, 返回 undefined

122. 输出什么?

const name = \"Lydia Hallie\";\n\nconsole.log(!typeof name === \"object\");\nconsole.log(!typeof name === \"string\");
  • A: false true
  • B: true false
  • C: false false
  • D: true true

答案

答案: C

typeof name 返回 \"string\"。字符串 \"string\" 是一个 truthy 的值,因此 !typeof name 返回一个布尔值 falsefalse === \"object\"false === \"string\" 都返回 false

(如果我们想检测一个值的类型,我们应该用 !== 而不是 !typeof

123. 输出什么?

const add = x => y => z => {\n\tconsole.log(x, y, z);\n\treturn x + y + z;\n};\n\nadd(4)(5)(6);
  • A: 4 5 6
  • B: 6 5 4
  • C: 4 function function
  • D: undefined undefined 6

答案

答案: A

函数 add 是一个返回 返回箭头函数的箭头函数 的箭头函数(still with me?)。第一个函数接收一个值为 4 的参数 x。我们调用第二个函数,它接收一个值为 5 的参数 y。然后我们调用第三个函数,它接收一个值为 6 的参数 z。当我们尝试在最后一个箭头函数中获取 x, yz 的值,JS 引擎根据作用域链去找 xy 的值。得到 4 5 6.

124. 输出什么?

async function* range(start, end) {\n\tfor (let i = start; i <= end; i++) {\n\t\tyield Promise.resolve(i);\n\t}\n}\n\n(async () => {\n\tconst gen = range(1, 3);\n\tfor await (const item of gen) {\n\t\tconsole.log(item);\n\t}\n})();
  • A: Promise {1} Promise {2} Promise {3}
  • B: Promise {<pending>} Promise {<pending>} Promise {<pending>}
  • C: 1 2 3
  • D: undefined undefined undefined

答案

答案: C

我们给 函数 range 传递: Promise{1}, Promise{2}, Promise{3},Generator 函数 range 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 gen,之后我们使用for await ... of 进行循环遍历。我们将返回的 Promise 实例赋值给 item: 第一个返回 Promise{1}, 第二个返回 Promise{2},之后是 Promise{3}。因为我们正 awaiting item 的值,resolved 状态的 promsie,promise 数组的 resolved 值 以此为: 123.

125. 输出什么?

const myFunc = ({ x, y, z }) => {\n\tconsole.log(x, y, z);\n};\n\nmyFunc(1, 2, 3);
  • A: 1 2 3
  • B: {1: 1} {2: 2} {3: 3}
  • C: { 1: undefined } undefined undefined
  • D: undefined undefined undefined

答案

答案: D

myFunc 期望接收一个包含 x, yz 属性的对象作为它的参数。因为我们仅仅传递三个单独的数字值 (1, 2, 3) 而不是一个含有 x, yz 属性的对象 ({x: 1, y: 2, z: 3}), x, yz 有着各自的默认值 undefined.

126. 输出什么?

function getFine(speed, amount) {\n  const formattedSpeed = new Intl.NumberFormat(\n    'en-US',\n    { style: 'unit', unit: 'mile-per-hour' }\n  ).format(speed)\n\n  const formattedAmount = new Intl.NumberFormat(\n    'en-US',\n    { style: 'currency', currency: 'USD' }\n  ).format(amount)\n\n  return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`\n}\n\nconsole.log(getFine(130, 300))
  • A: The driver drove 130 and has to pay 300
  • B: The driver drove 130 mph and has to pay $300.00
  • C: The driver drove undefined and has to pay undefined
  • D: The driver drove 130.00 and has to pay 300.00

答案

答案: B

通过方法 Intl.NumberFormat,我们可以格式化任意区域的数字值。我们对数字值 130 进行 mile-per-hour 作为 uniten-US 区域 格式化,结果为 130 mph。对数字值 300 进行 USD 作为 currentcyen-US 区域格式化,结果为 $300.00.

127. 输出什么?(null)



128. 输出什么?

const name = \"Lydia Hallie\";\nconst age = 21;\n\nconsole.log(Number.isNaN(name));\nconsole.log(Number.isNaN(age));\n\nconsole.log(isNaN(name));\nconsole.log(isNaN(age));
  • A: true false true false
  • B: true false false false
  • C: false false true false
  • D: false true false true

答案

答案: C

通过方法 Number.isNaN,你可以检测你传递的值是否为 数字值 并且是否等价于 NaNname 不是一个数字值,因此 Number.isNaN(name) 返回 falseage 是一个数字值,但它不等价于 NaN,因此 Number.isNaN(age) 返回 false.

通过方法 isNaN, 你可以检测你传递的值是否一个 number。name 不是一个 number,因此 isNaN(name) 返回 true. age 是一个 number 因此 isNaN(age) 返回 false.

129. 输出什么?

const randomValue = 21;\n\nfunction getInfo() {\n\tconsole.log(typeof randomValue);\n\tconst randomValue = \"Lydia Hallie\";\n}\n\ngetInfo();
  • A: \"number\"
  • B: \"string\"
  • C: undefined
  • D: ReferenceError

答案

答案: D

通过 const 关键字声明的变量在被初始化之前不可被引用:这被称之为 暂时性死区。在函数 getInfo 中,变量 randomValue 声明在getInfo 的作用域的此法环境中。在想要对 typeof randomValue 进行 log 之前,变量 randomValue 仍未被初始化: 错误ReferenceError 被抛出!JS 引擎并不会根据作用域链网上寻找该变量,因为我们已经在 getInfo 函数中声明了 randomValue 变量。

130. 输出什么?

const myPromise = Promise.resolve(\"Woah some cool data\");\n\n(async () => {\n\ttry {\n\t\tconsole.log(await myPromise);\n\t} catch {\n\t\tthrow new Error(`Oops didn't work`);\n\t} finally {\n\t\tconsole.log(\"Oh finally!\");\n\t}\n})();
  • A: Woah some cool data
  • B: Oh finally!
  • C: Woah some cool data Oh finally!
  • D: Oops didn't work Oh finally!

答案

答案: C

try 块区,我们打印 myPromise 变量的 awaited 值: \"Woah some cool data\"。因为try 块区没有错误抛出,catch 块区的代码并不执行。finally 块区的代码 总是 执行,\"Oh finally!\" 被输出。

131. 输出什么?(null)



132. 输出什么?

class Counter {\n\tconstructor() {\n\t\tthis.count = 0;\n\t}\n\n\tincrement() {\n\t\tthis.count++;\n\t}\n}\n\nconst counterOne = new Counter();\ncounterOne.increment();\ncounterOne.increment();\n\nconst counterTwo = counterOne;\ncounterTwo.increment();\n\nconsole.log(counterOne.count);
  • A: 0
  • B: 1
  • C: 2
  • D: 3

答案

答案: D

counterOne 是类 Counter 的一个实例。类 Counter 包含一个count 属性在它的构造函数里, 和一个 increment 方法。首先,我们通过 counterOne.increment() 调用方法 increment 两次。现在,counterOne.count2.


然后,我们创建一个新的变量 counterTwo 并将 counterOne 的引用地址赋值给它。因为对象受引用地址的影响,我们刚刚创建了一个新的对象,其引用地址和 counterOne 的等价。因此它们指向同一块内存地址,任何对其的副作用都会影响 counterTwo。现在 counterTwo.count2

我们调用 counterTwo.increment()count 的值设为 3。然后,我们打印 counterOne 里的 count,结果为 3


133. 输出什么?

const myPromise = Promise.resolve(Promise.resolve(\"Promise!\"));\n\nfunction funcOne() {\n\tmyPromise.then(res => res).then(res => console.log(res));\n\tsetTimeout(() => console.log(\"Timeout!\"), 0);\n\tconsole.log(\"Last line!\");\n}\n\nasync function funcTwo() {\n\tconst res = await myPromise;\n\tconsole.log(await res);\n\tsetTimeout(() => console.log(\"Timeout!\"), 0);\n\tconsole.log(\"Last line!\");\n}\n\nfuncOne();\nfuncTwo();
  • A: Promise! Last line! Promise! Last line! Last line! Promise!
  • B: Last line! Timeout! Promise! Last line! Timeout! Promise!
  • C: Promise! Last line! Last line! Promise! Timeout! Timeout!
  • D: Last line! Promise! Promise! Last line! Timeout! Timeout!

答案

答案: D

首先,我们调用 funcOne。在函数 funcOne 的第一行,我们调用myPromise promise 异步操作。当 JS 引擎在忙于执行 promise,它继续执行函数 funcOne。下一行 异步操作 setTimeout,其回调函数被 Web API 调用。 (详情请参考我关于 event loop 的文章.)

promise 和 timeout 都是异步操作,函数继续执行当 JS 引擎忙于执行 promise 和 处理 setTimeout 的回调。相当于 Last line! 首先被输出, 因为它不是异步操作。执行完 funcOne 的最后一行,promise 状态转变为 resolved,Promise! 被打印。然而,因为我们调用了 funcTwo(),调用栈不为空,setTimeout 的回调仍不能入栈。

我们现在处于 funcTwo,先 awaiting myPromise。通过 await 关键字, 我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 res 的 awaited 值(因为 promise 本身返回一个 promise)。 接着输出 Promise!

下一行就是 异步操作 setTimeout,其回调函数被 Web API 调用。

我们执行到函数 funcTwo 的最后一行,输出 Last line!。现在,因为 funcTwo 出栈,调用栈为空。在事件队列中等待的回调函数(() => console.log(\"Timeout!\") from funcOne, and () => console.log(\"Timeout!\") from funcTwo)以此入栈。第一个回调输出 Timeout!,并出栈。然后,第二个回调输出 Timeout!,并出栈。得到结果 Last line! Promise! Promise! Last line! Timeout! Timeout!

134. 我们怎样才能在 index.js 中调用 sum.js? 中的 sum

// sum.js\nexport default function sum(x) {\n\treturn x + x;\n}\n\n// index.js\nimport * as sum from \"./sum\";
  • A: sum(4)
  • B: sum.sum(4)
  • C: sum.default(4)
  • D: 默认导出不用 * 来导入,只能具名导出

答案

答案: C

使用符号 *,我们引入文件中的所有值,包括默认和具名。如果我们有以下文件:

// info.js\nexport const name = \"Lydia\";\nexport const age = 21;\nexport default \"I love JavaScript\";\n\n// index.js\nimport * as info from \"./info\";\nconsole.log(info);

将会输出以下内容:

{\n  default: \"I love JavaScript\",\n  name: \"Lydia\",\n  age: 21\n}

sum 为例,相当于以下形式引入值 sum

{ default: function sum(x) { return x + x } }

我们可以通过调用 sum.default 来调用该函数

135. 输出什么?

const handler = {\n\tset: () => console.log(\"Added a new property!\"),\n\tget: () => console.log(\"Accessed a property!\")\n};\n\nconst person = new Proxy({}, handler);\n\nperson.name = \"Lydia\";\nperson.name;
  • A: Added a new property!
  • B: Accessed a property!
  • C: Added a new property! Accessed a property!
  • D: 没有任何输出

答案

答案: C

使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 handler : set and get。每当我们 设置 属性值时 set 被调用,每当我们 获取 时 get 被调用。

第一个参数是一个空对象 {},作为 person 的值。对于这个对象,自定义行为被定义在对象 handler。如果我们向对象 person 添加属性,set 将被调用。如果我们获取 person 的属性,get 将被调用。

首先,我们向 proxy 对象 (person.name = \"Lydia\") 添加一个属性 nameset 被调用并输出 \"Added a new property!\"

然后,我们获取 proxy 对象的一个属性,对象 handler 的属性 get 被调用。输出 \"Accessed a property!\"

136. 以下哪一项会对对象 person 有副作用?

const person = { name: \"Lydia Hallie\" };\n\nObject.seal(person);
  • A: person.name = \"Evan Bacon\"
  • B: person.age = 21
  • C: delete person.name
  • D: Object.assign(person, { age: 21 })

答案

答案: A

使用 Object.seal 我们可以防止新属性 被添加,或者存在属性 被移除.

然而,你仍然可以对存在属性进行更改。

137. 以下哪一项会对对象 person 有副作用?

const person = {\n\tname: \"Lydia Hallie\",\n\taddress: {\n\t\tstreet: \"100 Main St\"\n\t}\n};\n\nObject.freeze(person);
  • A: person.name = \"Evan Bacon\"
  • B: delete person.address
  • C: person.address.street = \"101 Main St\"
  • D: person.pet = { name: \"Mara\" }

答案

答案: C

使用方法 Object.freeze 对一个对象进行 冻结。不能对属性进行添加,修改,删除。

然而,它仅 对对象进行 浅 冻结,意味着只有 对象中的 直接 属性被冻结。如果属性是另一个 object,像案例中的 addressaddress 中的属性没有被冻结,仍然可以被修改。

138. 输出什么?

const add = x => x + x;\n\nfunction myFunc(num = 2, value = add(num)) {\n\tconsole.log(num, value);\n}\n\nmyFunc();\nmyFunc(3);
  • A: 2 4 and 3 6
  • B: 2 NaN and 3 NaN
  • C: 2 Error and 3 6
  • D: 2 4 and 3 Error

答案

答案: A

首先我们不传递任何参数调用 myFunc()。因为我们没有传递参数,numvalue 获取它们各自的默认值:num 为 2,而 value 为函数 add 的返回值。对于函数 add,我们传递值为 2 的 num 作为参数。函数 add 返回 4 作为 value 的值。

然后,我们调用 myFunc(3) 并传递值 3 参数 num 的值。我们没有给 value 传递值。因为我们没有给参数 value 传递值,它获取默认值:函数 add 的返回值。对于函数 add,我们传递值为 3 的 num给它。函数 add 返回 6 作为 value 的值。

139. 输出什么?

class Counter {#number = 10\n\n  increment() {\n    this.#number++\n  }\n\n  getNum() {\n    return this.#number\n  }\n}\n\nconst counter = new Counter()\ncounter.increment()\n\nconsole.log(counter.#number)
  • A: 10
  • B: 11
  • C: undefined
  • D: SyntaxError

答案

答案: D

在 ES2020 中,通过 # 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 counter.#number,语法错误被抛出:我们无法在 class Counter 外部获取它!

140. 选择哪一个?

const teams = [\n\t{ name: \"Team 1\", members: [\"Paul\", \"Lisa\"] },\n\t{ name: \"Team 2\", members: [\"Laura\", \"Tim\"] }\n];\n\nfunction* getMembers(members) {\n\tfor (let i = 0; i < members.length; i++) {\n\t\tyield members[i];\n\t}\n}\n\nfunction* getTeams(teams) {\n\tfor (let i = 0; i < teams.length; i++) {\n\t\t// ✨ SOMETHING IS MISSING HERE ✨\n\t}\n}\n\nconst obj = getTeams(teams);\nobj.next(); // { value: \"Paul\", done: false }\nobj.next(); // { value: \"Lisa\", done: false }
  • A: yield getMembers(teams[i].members)
  • B: yield* getMembers(teams[i].members)
  • C: return getMembers(teams[i].members)
  • D: return yield getMembers(teams[i].members)

答案

答案: B

为了遍历 teams 数组中对象的属性 members 中的每一项,我们需要将 teams[i].members 传递给 Generator 函数 getMembers。Generator 函数返回一个 generator 对象。为了遍历这个 generator 对象中的每一项,我们需要使用 yield*.

如果我们没有写 yieldreturn yield 或者 return,整个 Generator 函数不会第一时间 return 当我们调用 next 方法。

141. 输出什么?

const person = {\n\tname: \"Lydia Hallie\",\n\thobbies: [\"coding\"]\n};\n\nfunction addHobby(hobby, hobbies = person.hobbies) {\n\thobbies.push(hobby);\n\treturn hobbies;\n}\n\naddHobby(\"running\", []);\naddHobby(\"dancing\");\naddHobby(\"baking\", person.hobbies);\n\nconsole.log(person.hobbies);
  • A: [\"coding\"]
  • B: [\"coding\", \"dancing\"]
  • C: [\"coding\", \"dancing\", \"baking\"]
  • D: [\"coding\", \"running\", \"dancing\", \"baking\"]

答案

答案: C

函数 addHobby 接受两个参数,hobby 和有着对象 person 中数组 hobbies 默认值的 hobbies

首相,我们调用函数 addHobby,并给 hobby 传递 \"running\" 以及给 hobbies 传递一个空数组。因为我们给 hobbies 传递了空数组,\"running\" 被添加到这个空数组。

然后,我们调用函数 addHobby,并给 hobby 传递 \"dancing\"。我们不向 hobbies 传递值,因此它获取其默认值 —— 对象 person 的 属性 hobbies。我们向数组 person.hobbies push dancing

最后,我们调用函数 addHobby,并向 hobby 传递 值 \"bdaking\",并且向 hobbies 传递 person.hobbies。我们向数组 person.hobbies push dancing

pushing dancingbaking 之后,person.hobbies 的值为 [\"coding\", \"dancing\", \"baking\"]

142. 输出什么?(null)



143. 哪一个选项会导致报错?(null)


  • A: 1
  • B: 1 and 2
  • C: 3 and 4
  • D: 3


答案

答案: D

const 关键字意味着我们不能 重定义 变量中的值,它 仅可读。而然,值本身不可修改。数组 emojis 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。

144. 我们需要向对象 person 添加什么,以致执行 [...person] 时获得形如 [\"Lydia Hallie\", 21] 的输出?

const person = {\n  name: \"Lydia Hallie\",\n  age: 21\n}\n\n[...person] // [\"Lydia Hallie\", 21]
  • A: 不需要,对象默认就是可迭代的
  • B: *[Symbol.iterator]() { for (let x in this) yield* this[x] }
  • C: *[Symbol.iterator]() { yield* Object.values(this) }
  • D: *[Symbol.iterator]() { for (let x in this) yield this }

答案

答案: C

对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器 symbol [Symbol.iterator] 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 *[Symbol.iterator]() {}。如果我们想要返回数组 [\"Lydia Hallie\", 21]: yield* Object.values(this),这个 generator 函数一定要 yield 对象 personObject.values

145. 输出什么?

let count = 0;\nconst nums = [0, 1, 2, 3];\n\nnums.forEach(num => {\n\tif (num) count += 1\n})\n\nconsole.log(count)
  • A: 1
  • B: 2
  • C: 3
  • D: 4

答案

答案: C

forEach 循环内部的 if 会判断 num 的值是 truthy 或者是 falsy。因为 nums 数组的第一个数字是 0,一个 falsy 值, if 语句代码块不会被执行。count 仅仅在 nums 数组的其他 3 个数字 123 时加 1。因为 count 执行了 3 次加 1 运算,所以 count 的值为 3

146. 输出是什么?(null)


147. 输出什么?

class Calc {\n\tconstructor() {\n\t\tthis.count = 0 \n\t}\n\n\tincrease() {\n\t\tthis.count ++\n\t}\n}\n\nconst calc = new Calc()\nnew Calc().increase()\n\nconsole.log(calc.count)
  • A: 0
  • B: 1
  • C: undefined
  • D: ReferenceError

答案

答案: A

我们设置 calc 变量为 Calc 类的一个新实例。 然后,我们初始化一个 Calc 的新实例,而且调用了这个实例的 increase 方法。因为 count 属性是在 Calc class 的 constructor 内部的,所以 count 属性不会在 Calc 的原型链上共享出去。这就意味着 calc 实例的 count 值不会被更新,count 仍然是 0

148. 输出什么?

const user = {\n\temail: \"e@mail.com\",\n\tpassword: \"12345\"\n}\n\nconst updateUser = ({ email, password }) => {\n\tif (email) {\n\t\tObject.assign(user, { email })\n\t}\n\n\tif (password) {\n\t\tuser.password = password\n\t}\n\n\treturn user\n}\n\nconst updatedUser = updateUser({ email: \"new@email.com\" })\n\nconsole.log(updatedUser === user)
  • A: false
  • B: true
  • C: TypeError
  • D: ReferenceError

答案

答案: B

updateUser 函数更新 user 的 emailpassword 属性的值, 如果它们的值传入函数, 函数返回的就是 user 对象。 updateUser 函数的返回值是 user 对象,意味着 updatedUser 的值与 user 指向的是同一个 user 对象。updatedUser === usertrue.

149. 输出什么?(null)



150. 输出什么?(null)



151. 输出什么?

const user = {\n\temail: \"my@email.com\",\n\tupdateEmail: email => {\n\t\tthis.email = email\n\t}\n}\n\nuser.updateEmail(\"new@email.com\")\nconsole.log(user.email)
  • A: my@email.com
  • B: new@email.com
  • C: undefined
  • D: ReferenceError

答案

答案: A

updateEmail 函数是一个箭头函数,它没有和 user 对象绑定。这就意味着 this 关键字不会引用到 user 对象,但是会引用到全局对象。 user 对象内部的 email 的值不会更新。当打印 user.email 的时候, 原始值 my@email.com 被返回。

152. 输出什么?

const promise1 = Promise.resolve('First')\nconst promise2 = Promise.resolve('Second')\nconst promise3 = Promise.reject('Third')\nconst promise4 = Promise.resolve('Fourth')\n\nconst runPromises = async () => {\n\tconst res1 = await Promise.all([promise1, promise2])\n\tconst res2  = await Promise.all([promise3, promise4])\n\treturn [res1, res2]\n}\n\nrunPromises()\n\t.then(res => console.log(res))\n\t.catch(err => console.log(err))
  • A: [['First', 'Second'], ['Fourth']]
  • B: [['First', 'Second'], ['Third', 'Fourth']]
  • C: [['First', 'Second']]
  • D: 'Third'

答案

答案: D

Promise.all 方法可以并行式运行 promise。如果其中一个 promise 失败了,Promise.all 方法会带上被 reject 的 promise 的值rejects。在这个例子中, promise3 带着 \"Third\" 值 reject。我们在调用 runPromises 时在 runPromises 函数内部的 catch 方法去捕获任意 error 从而捕获到被 reject 的值。因为 promise3 带着 \"Third\" 被 reject,所以只有 \"Third\" 打印。

153. 哪个作为method的值可以打印{ name: \"Lydia\", age: 22 }?

const keys = [\"name\", \"age\"]\nconst values = [\"Lydia\", 22]\n\nconst method = /* ?? */\nObject[method](keys.map((_, i) => {\n\treturn [keys[i], values[i]]\n})) // { name: \"Lydia\", age: 22 }
  • A: entries
  • B: values
  • C: fromEntries
  • D: forEach

答案

答案: C

fromEntries 方法可以将二维数组转换为对象。在每个子数组的第一个元素是 key,在每个子数组的第二个元素是 value。在这个例子中,我们映射了 keys 数组,它返回了一个数组,数组的第一个元素为 keys 数组当前索引的值,第二个元素为 values 数组当前索引的值。

这样就创建了一个包含正确 keys 和 values 的子数组的数组,因此结果为{ name: \"Lydia\", age: 22 }

154. 输出什么?

const createMember = ({ email, address = {}}) => {\n\tconst validEmail = /.+\\@.+\\..+/.test(email)\n\tif (!validEmail) throw new Error(\"Valid email pls\")\n\n\treturn {\n\t\temail,\n\t\taddress: address ? address : null\n\t}\n}\n\nconst member = createMember({ email: \"my@email.com\" })\nconsole.log(member)
  • A: { email: \"my@email.com\", address: null }
  • B: { email: \"my@email.com\" }
  • C: { email: \"my@email.com\", address: {} }
  • D: { email: \"my@email.com\", address: undefined }

答案

答案: C

address 的默认值是一个空对象 {}。当我们设置 member 变量为 createMember 函数返回的对象,我们没有为 address 参数传值,意味着 address 的值为默认的空对象 {}。一个空对象是一个 truthy 值,意味着 address ? address : null 条件会返回 true。address 的值为空对象 {}

155. 输出什么?

let randomValue = { name: \"Lydia\" }\nrandomValue = 23\n\nif (!typeof randomValue === \"string\") {\n\tconsole.log(\"It's not a string!\")\n} else {\n\tconsole.log(\"Yay it's a string!\")\n}
  • A: It's not a string!
  • B: Yay it's a string!
  • C: TypeError
  • D: undefined

答案

答案: B

if 语句的条件判断 !typeof randomValue 的值是否等于 \"string\"! 操作符将这个值转化为一个布尔值。如果值是 truthy 的话,返回值会是 false,如果值是 falsy,返回值会是 true。在这里, typeof randomValue 的返回值是一个 truthy 值 \"number\",意味着 !typeof randomValue 的值是一个布尔值 false

!typeof randomValue === \"string\" 总是返回 false,因为我们实际上是在执行 false === \"string\"。因为条件返回的是 false,所以 else 语句中的代码块会被运行,因此打印 Yay it's a string! 。


1/0