Home Web Front-end JS Tutorial 23 JavaScript interview questions you need to know

23 JavaScript interview questions you need to know

May 16, 2016 pm 03:23 PM
javascript Interview questions

23 JavaScript interview questions you need to know

1. Using typeof bar === "object" to determine whether bar is an object has some potential drawbacks? How to avoid this drawback?

The disadvantages of using typeof are obvious (this disadvantage is the same as using instanceof):

let obj = {};
let arr = [];
 
console.log(typeof obj === 'object'); //true
console.log(typeof arr === 'object'); //true
console.log(typeof null === 'object'); //true
Copy after login

From the above output results, it can be seen that typeof bar === "object" does not It cannot be accurately determined that bar is an Object. You can avoid this drawback by Object.prototype.toString.call(bar) === "[object Object]":

let obj = {};
let arr = [];
 
console.log(Object.prototype.toString.call(obj)); //[object Object]
console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(Object.prototype.toString.call(null)); //[object Null]
Copy after login

In addition, in order to cherish life, please stay away from ==:

And [] === false returns false.

Recommended related articles: The most complete collection of js interview questions in 2020 (latest)

2. Will the following code output a message on the console? Why?

(function(){
 var a = b = 3;
})();
 
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
Copy after login

This is related to the variable scope. The output is changed to the following:

console.log(b); //3
console,log(typeof a); //undefined
Copy after login

Disassemble the variable assignment in the self-executing function:

b = 3;
var a = b;
Copy after login

So b becomes a global variable, and a is a local variable of the self-executing function.

3. Will the following code output a message on the console? Why?

var myObject = {
 foo: "bar",
 func: function() {
 var self = this;
 console.log("outer func: this.foo = " + this.foo);
 console.log("outer func: self.foo = " + self.foo);
 (function() {
 console.log("inner func: this.foo = " + this.foo);
 console.log("inner func: self.foo = " + self.foo);
 }());
Copy after login

It is not difficult to judge the first and second outputs. Before ES6, JavaScript only had function scope, so the IIFE in func has its own independent scope, and it can Self in the external scope is accessed, so the third output will report an error because this is undefined in the accessible scope, and the fourth output is bar. If you know closures, it is easy to solve:

function(test) {
 console.log("inner func: this.foo = " + test.foo); //'bar'
 console.log("inner func: self.foo = " + self.foo);
}(self));
Copy after login

If you are not familiar with closures, you can refer to this article: Talking about closures from the scope chain

4. Convert JavaScript code What does it mean to include it in a function block? Why do this?

In other words, why use Immediately-Invoked Function Expression?

IIFE has two classic usage scenarios, one is similar to regularly outputting data items in a loop, and the other is similar to JQuery/Node plug-in and module development.

for(var i = 0; i < 5; i++) {
 setTimeout(function() {
 console.log(i);
 }, 1000);
}
Copy after login

The above output is not 0, 1, 2, 3, 4 as you thought, but all the output is 5, then IIFE can be useful:

for(var i = 0; i < 5; i++) {
 (function(i) {
 setTimeout(function() {
 console.log(i);
 }, 1000);
 })(i)
}
Copy after login

In the development of JQuery/Node plug-ins and modules, in order to avoid variable pollution, it is also a big IIFE:

(function($) {
 //代码
 } )(jQuery);
Copy after login

5. Perform JavaScript in strict mode ('use strict') What are the benefits of development?

Eliminate some unreasonable and imprecise aspects of Javascript syntax, and reduce some weird behaviors;

Eliminate some unsafe aspects of code running, and ensure the safety of code running;

Improve compiler efficiency and increase running speed;

pave the way for new versions of Javascript in the future.

6. Are the return values ​​of the following two functions the same? Why?

The first is to raise the power first and then lower the power:

function add(num1, num2){
 let r1, r2, m;
 r1 = (&#39;&#39;+num1).split(&#39;.&#39;)[1].length;
 r2 = (&#39;&#39;+num2).split(&#39;.&#39;)[1].length;
 
 m = Math.pow(10,Math.max(r1,r2));
 return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756
Copy after login

The second is to use the built-in toPrecision() and toFixed() methods. Note that the return value string of the method .

function add(x, y) {
 return x.toPrecision() + y.toPrecision()
}
console.log(add(0.1,0.2)); //"0.10.2"
Copy after login

7. Implement the function isInteger(x) to determine whether x is an integer

You can convert x into decimal and determine whether it is equal to itself. That's it:

function isInteger(x) {
 return parseInt(x, 10) === x;
}
Copy after login

ES6 extends the numerical value and provides the static method isInteger() to determine whether the parameter is an integer:

Number.isInteger(25) // true
Number.isInteger(25.0) // true
Number.isInteger(25.1) // false
Number.isInteger("15") // false
Number.isInteger(true) // false
Copy after login

The range of integers that JavaScript can accurately represent is Between -2^53 and 2^53 (excluding the two endpoints), beyond this range, the value cannot be accurately represented. ES6 introduced two constants, Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER, to represent the upper and lower limits of this range, and provided Number.isSafeInteger() to determine whether an integer is a safe integer.

8. In the following code, in what order will the numbers 1-4 be output? Why is it output like this?

(function() {
 console.log(1);
 setTimeout(function(){console.log(2)}, 1000);
 setTimeout(function(){console.log(3)}, 0);
 console.log(4);
})();
Copy after login
Copy after login

I won’t explain this much, it’s mainly JavaScript’s timing mechanism and time loop. Don’t forget, JavaScript is single-threaded. For detailed explanation, please refer to Talking about JavaScript running mechanism from setTimeout.

9. Write a function with less than 80 characters to determine whether a string is a palindrome string

function isPalindrome(str) {
 str = str.replace(/\W/g, &#39;&#39;).toLowerCase();
 return (str == str.split(&#39;&#39;).reverse().join(&#39;&#39;));
}
Copy after login
Copy after login

I encountered this question on codewars and included some A good solution, you can click here: Palindrome For Your Dome

10. Write a sum method that can work normally when called in the following way

console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
Copy after login
Copy after login

Aimed at This question can be solved by judging the number of parameters:

function sum() {
 var fir = arguments[0];
 if(arguments.length === 2) {
 return arguments[0] + arguments[1]
 } else {
 return function(sec) {
 return fir + sec;
 }
 }
  
}
Copy after login
Copy after login

11. Answer the following questions based on the code snippet below

for (var i = 0; i < 5; i++) {
 var btn = document.createElement(&#39;button&#39;);
 btn.appendChild(document.createTextNode(&#39;Button &#39; + i));
 btn.addEventListener(&#39;click&#39;, function(){ console.log(i); });
 document.body.appendChild(btn);
}
Copy after login

1. Click Button 4. What will be output on the console?

Clicking any one of the 5 buttons will output 5

2. Give an expected implementation

Refer to IIFE.

12. What will the following code output? Why?

var arr1 = "john".split(&#39;&#39;); j o h n
var arr2 = arr1.reverse(); n h o j
var arr3 = "jones".split(&#39;&#39;); j o n e s
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
Copy after login

What will be output? You will know it after running it, and it may be unexpected.

reverse() will change the array itself and return a reference to the original array. For usage of

slice, please refer to: slice

13. What will the following code output? Why?

console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log( "A" - "B" + "2");
console.log( "A" - "B" + 2);
Copy after login

输出什么,自己去运行吧,需要注意三个点:

多个数字和数字字符串混合运算时,跟操作数的位置有关

console.log(2 + 1 + &#39;3&#39;); / /‘33&#39;
console.log(&#39;3&#39; + 2 + 1); //&#39;321&#39;
Copy after login

数字字符串之前存在数字中的正负号(+/-)时,会被转换成数字

console.log(typeof &#39;3&#39;); // string
console.log(typeof +&#39;3&#39;); //number
Copy after login

同样,可以在数字前添加 '',将数字转为字符串

console.log(typeof 3); // number
console.log(typeof (&#39;&#39;+3)); //string
Copy after login

对于运算结果不能转换成数字的,将返回 NaN

console.log(&#39;a&#39; * &#39;sd&#39;); //NaN
console.log(&#39;A&#39; - &#39;B&#39;); // NaN
Copy after login

14、什么是闭包?举例说明

可以参考此篇:从作用域链谈闭包

15、下面的代码会输出什么?为啥?

for (var i = 0; i < 5; i++) {
 setTimeout(function() { console.log(i); }, i * 1000 );
}
Copy after login

请往前面翻,参考第4题,解决方式已经在上面了

16、解释下列代码的输出

console.log("0 || 1 = "+(0 || 1));
console.log("1 || 2 = "+(1 || 2));
console.log("0 && 1 = "+(0 && 1));
console.log("1 && 2 = "+(1 && 2));
Copy after login

逻辑与和逻辑或运算符会返回一个值,并且二者都是短路运算符:

逻辑与返回第一个是 false 的操作数 或者 最后一个是 true的操作数

console.log(1 && 2 && 0); //0
console.log(1 && 0 && 1); //0
console.log(1 && 2 && 3); //3
Copy after login

如果某个操作数为 false,则该操作数之后的操作数都不会被计算

逻辑或返回第一个是 true 的操作数 或者 最后一个是 false的操作数

console.log(1 || 2 || 0); //1
console.log(0 || 2 || 1); //2
console.log(0 || 0 || false); //false
Copy after login

如果某个操作数为 true,则该操作数之后的操作数都不会被计算

如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高:

console.log(1 && 2 || 0); //2
console.log(0 || 2 && 1); //1
console.log(0 && 2 || 1); //1
Copy after login

在 JavaScript,常见的 false 值:

0, '0', +0, -0, false, '',null,undefined,null,NaN

要注意空数组([])和空对象({}):

console.log([] == false) //true
console.log({} == false) //false
console.log(Boolean([])) //true
console.log(Boolean({})) //true
Copy after login

所以在 if 中,[] 和 {} 都表现为 true:

17、解释下面代码的输出

console.log(false == &#39;0&#39;)
console.log(false === &#39;0&#39;)
Copy after login

18、解释下面代码的输出

var a={},
 b={key:&#39;b&#39;},
 c={key:&#39;c&#39;};
 
a[b]=123;
a[c]=456;
 
console.log(a[b]);
输出是456。
Copy after login

19、在下面的代码中,数字 1-4 会以什么顺序输出?为什么会这样输出?

(function() {
 console.log(1);
 setTimeout(function(){console.log(2)}, 1000);
 setTimeout(function(){console.log(3)}, 0);
 console.log(4);
})();
Copy after login
Copy after login

这个就不多解释了,主要是 JavaScript 的定时机制和时间循环,不要忘了,JavaScript 是单线程的。详解可以参考 从setTimeout谈JavaScript运行机制。

20、写一个少于 80 字符的函数,判断一个字符串是不是回文字符串

function isPalindrome(str) {
 str = str.replace(/\W/g, &#39;&#39;).toLowerCase();
 return (str == str.split(&#39;&#39;).reverse().join(&#39;&#39;));
}
Copy after login
Copy after login

这个题我在 codewars 上碰到过,并收录了一些不错的解决方式,可以戳这里:Palindrome For Your Dome

21、写一个按照下面方式调用都能正常工作的 sum 方法

console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
Copy after login
Copy after login

针对这个题,可以判断参数个数来实现:

function sum() {
 var fir = arguments[0];
 if(arguments.length === 2) {
 return arguments[0] + arguments[1]
 } else {
 return function(sec) {
 return fir + sec;
 }
 }
  
}
Copy after login
Copy after login

22、解释下面代码的输出,并修复存在的问题

var hero = {
 _name: &#39;John Doe&#39;,
 getSecretIdentity: function (){
 return this._name;
 }
};
 
var stoleSecretIdentity = hero.getSecretIdentity;
 
console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());
Copy after login

将 getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数:

var stoleSecretIdentity = function (){
 return this._name;
}
stoleSecretIdentity
Copy after login

的上下文是全局环境,所以第一个输出 undefined。若要输出 John Doe,则要通过 call 、apply 和 bind 等方式改变 stoleSecretIdentity 的this 指向(hero)。

第二个是调用对象的方法,输出 John Doe。

23、给你一个 DOM 元素,创建一个能访问该元素所有子元素的函数,并且要将每个子元素传递给指定的回调函数。

函数接受两个参数:

DOM

指定的回调函数

原文利用 深度优先搜索(Depth-First-Search) 给了一个实现:

function Traverse(p_element,p_callback) {
 p_callback(p_element);
 var list = p_element.children;
 for (var i = 0; i < list.length; i++) {
 Traverse(list[i],p_callback); // recursive call
 }
}
Copy after login

相关学习推荐:javascript视频教程

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles