Home  >  Article  >  Web Front-end  >  Share 10 Quiz Questions and Answers to Improve Your JavaScript Skills

Share 10 Quiz Questions and Answers to Improve Your JavaScript Skills

青灯夜游
青灯夜游forward
2020-06-20 09:12:241552browse

Share 10 Quiz Questions and Answers to Improve Your JavaScript Skills

Writing questions is a good way for us to improve our skills. The following questions are challenging and "guided". If you know how to answer, that means you're pretty good, but if you find yourself answering wrong and can figure out why it's wrong, I think that's even better!

Recommended learning: JavaScript video tutorial , js tutorial (picture and text)

1 . Array sorting comparison

#Look at the following array, what is the output after various sorting operations?

const arr1 = ['a', 'b', 'c'];
const arr2 = ['b', 'c', 'a'];

console.log(
  arr1.sort() === arr1,
  arr2.sort() == arr2,
  arr1.sort() === arr2.sort()
);

Answer and analysis

##Answer: true, true, false

There are several concepts at play here. First, array's

sort method sorts the original array and returns a reference to the array. This means that when you call arr2.sort(), the objects within the arr2 array will be sorted.

When you compare objects, the sort order of the arrays does not matter. Since

arr1.sort() and arr1 point to the same object in memory, the first equality test returns true. The same goes for the second comparison: arr2.sort() and arr2 point to the same object in memory.

In the third test,

arr1.sort() and arr2.sort() have the same sort order; however, they point to different objects in memory . Therefore, the third test evaluates to false.

2. Set object

Convert the following

Set object into a new array, and what is the final output? ?

const mySet = new Set([{ a: 1 }, { a: 1 }]);
const result = [...mySet];
console.log(result);

Answer and analysis

Answer: [{a: 1 }, {a: 1}]

Although Set objects do remove duplicates, the two values ​​we create with Set are references to different objects in memory, even though they have the same key value pair. This is the same reason why

{ a: 1 } === { a: 1 } results in false.

If the set is created with object variables, for example

obj = {a: 1}, new Set([obj, obj]) will have only one element , because both elements in the array refer to the same object in memory.

3. Mutability of deep objects

The following objects represent the user Joe and his dog Buttercup. We save the object using

Object.freeze and then try to change Buttercup's name. What will be the final output?

const user = {
  name: 'Joe',
  age: 25,
  pet: {
    type: 'dog',
    name: 'Buttercup',
  },
};

Object.freeze(user);

user.pet.name = 'Daffodil';

console.log(user.pet.name);

Answer and analysis

Answer: Daffodil

Object.freeze will shallowly freeze the object, but will not protect deep properties from being modified. In this example, user.age cannot be modified, but user.pet.name can be modified without issue. If we feel we need to protect an object from being changed "from start to finish", we can apply Object.freeze recursively or use an existing "deep freeze" library.

4. Prototypal inheritance

In the following code, there is a

Dog constructor. Our dog obviously has the speak operation. What is the output when we call Pogo's speak?

function Dog(name) {
  this.name = name;
  this.speak = function() {
    return 'woof';
  };
}

const dog = new Dog('Pogo');

Dog.prototype.speak = function() {
  return 'arf';
};

console.log(dog.speak());

Answer and analysis

Answer: woof

每次创建一个新的 Dog 实例时,我们都会将该实例的 speak 属性设置为返回字符串 woof 的函数。由于每次我们创建一个新的Dog实例时都要设置该值,因此解释器不会沿着原型链去找 speak 属性。结果就不会使用 Dog.prototype.speak 上的  speak 方法。

5. Promise.all 的解决顺序

在这个问题中,我们有一个 timer 函数,它返回一个 Promise ,该 Promise 在随机时间后解析。我们用 Promise.all 解析一系列的 timer。最后的输出是什么,是随机的吗?

const timer = a => {
  return new Promise(res =>
    setTimeout(() => {
      res(a);
    }, Math.random() * 100)
  );
};

const all = Promise.all([timer('first'), timer('second')]).then(data =>
  console.log(data)
);

答案和解析

答案: ["first", "second"]

Promise 解决的顺序与 Promise.all 无关。我们能够可靠地依靠它们按照数组参数中提供的相同顺序返回。

6. Reduce 数学

数学时间!输出什么?

const arr = [x => x * 1, x => x * 2, x => x * 3, x => x * 4];

console.log(arr.reduce((agg, el) => agg + el(agg), 1));

答案和解析

答案: 120

使用 Array#reduce 时,聚合器的初始值(在此称为 agg)在第二个参数中给出。在这种情况下,该值为 1。然后可以如下迭代函数:

1 + 1 * 1 = 2(下一次迭代中聚合器的值)

2 + 2 * 2 = 6(下一次迭代中聚合器的值)

6 + 6 * 3 = 24(下一次迭代中聚合器的值)

24 + 24 * 4 = 120(最终值)

因此它是 120。

7. 短路通知(Short-Circuit Notification(s))

让我们向用户显示一些通知。以下代码段输出了什么?

const notifications = 1;

console.log(
  `You have ${notifications} notification${notifications !== 1 && 's'}`
);

答案和解析

答案:“You have 1 notificationfalse”

不幸的是,我们的短路评估将无法按预期工作: notifications !== 1 && 's'  评估为 false,这意味着我们实际上将会输出 You have 1 notificationfalse。如果希望代码段正常工作,则可以考虑条件运算符: ${notifications === 1 ? '' : 's'}

8. 展开操作和重命名

查看以下代码中有单个对象的数组。当我们扩展该数组并更改 0 索引对象上的 firstname 属性时会发生什么?

const arr1 = [{ firstName: 'James' }];
const arr2 = [...arr1];
arr2[0].firstName = 'Jonah';

console.log(arr1);

答案和解析

答案: [{ firstName: "Jonah" }]

展开操作符会创建数组的浅表副本,这意味着 arr2 中包含的对象与 arr1 所指向的对象相同。所以在一个数组中修改对象的 firstName 属性,也将会在另一个数组中更改。

9. 数组方法绑定

在以下情况下会输出什么?

const map = ['a', 'b', 'c'].map.bind([1, 2, 3]);
map(el => console.log(el));

答案和解析

答案: 1 2 3

['a', 'b', 'c'].map 被调用时,将会调用 this' 值为 '['a','b','c']Array.prototype.map。但是当用作 引用 时, Array.prototype.map 的引用。

Function.prototype.bind 会将函数的 this 绑定到第一个参数(在本例中为 [1, 2, 3]),用 this 调用Array.prototype.map 将会导致这些项目被迭代并输出。

10. set 的唯一性和顺序

在下面的代码中,我们用 set 对象和扩展语法创建了一个新数组,最后会输出什么?

const arr = [...new Set([3, 1, 2, 3, 4])];
console.log(arr.length, arr[2]);

答案和解析

答案: 4  2

set 对象会强制里面的元素唯一(集合中已经存在的重复元素将会被忽略),但是不会改变顺序。所以 arr 数组的内容是 [3,1,2,4]arr.length4,且 arr[2](数组的第三个元素)为 2

英文原文地址:https://typeofnan.dev/10-javascript-quiz-questions-and-answers/

作者:Nick Scialli

想要获取炫酷的页面特效,可访问:js代码特效 栏目!!

The above is the detailed content of Share 10 Quiz Questions and Answers to Improve Your JavaScript Skills. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete