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'ssort 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.
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.
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 followingSet 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}]
{ a: 1 } === { a: 1 } results in
false.
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 usingObject.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 aDog 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.length
为 4
,且 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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
