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

Share 10 Quiz Questions and Answers to Improve Your JavaScript Skills

Jun 20, 2020 am 09:12 AM
javascript

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()
);
Copy after login

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);
Copy after login

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);
Copy after login

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());
Copy after login

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)
);
Copy after login

答案和解析

答案: ["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));
Copy after login

答案和解析

答案: 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'}`
);
Copy after login

答案和解析

答案:“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);
Copy after login

答案和解析

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

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

9. 数组方法绑定

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

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

答案和解析

答案: 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]);
Copy after login

答案和解析

答案: 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles