Home >Web Front-end >JS Tutorial >24 JavaScript interview questions
Nowadays, more and more people choose the programmer industry. When we finish our studies, we will go out to find jobs, so some people will inevitably feel very uncomfortable during the interview. Nervous and timid. During a programmer interview, in addition to the interviewer, there are also interview questions specifically designed to assess your ability, so this article is about 24 JavaScript interview questions. Now friends, there is a benefit, so hurry up and get it!
Recommended related articles:The most complete collection of js interview questions in 2020 (latest)
1. There are some potential disadvantages in using typeof bar === "object" to determine whether bar is an object? How to avoid this drawback?
let obj = {};let arr = [];console.log(typeof obj === 'object'); //trueconsole.log(typeof arr === 'object'); //trueconsole.log(typeof null === 'object'); //tru
It can be seen from the above output that typeof bar === "object" cannot accurately determine 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]
2. Will the following code output something wrong on the console? Why?
(function(){ var a = b = 3;})();console.log("a defined? " + (typeof a !== 'undefined')); console.log("b defined? " + (typeof b !== 'undefined'));
This is related to the variable scope. The output is changed to the following:
console.log(b); //3console,log(typeof a); //undefined
Disassemble the variable assignment in the self-executing function:
b = 3;var a = b;
So b becomes a global variable, and a is a local variable of the self-executing function.
3. What will the following code output to 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); }()); }};myObject.func();
The first and second outputs are not difficult to judge. Before ES6, JavaScript only had function scope, so the IIFE in func had its own independent scope, and it could access the external scope. self in , 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));
If you are not familiar with closures, you can click here: Talking about closures from the scope chain
4. Include JavaScript code in What does a function block mean? 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);}
The above output is not 0, 1, 2, 3, 4 as you think, 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)}
And in JQuery In the development of /Node plug-ins and modules, it is also a big IIFE to avoid variable pollution:
(function($) { //代码 } )(jQuery);
5. What are the benefits of developing JavaScript in strict mode ('use strict')?
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?
function foo1(){ return { bar: "hello" };}function foo2(){ return { bar: "hello" };}
In programming languages, semicolons (;) are basically used to separate statements, which can increase the readability and neatness of the code. In JS, if each statement occupies a separate line, you can usually omit the semicolon (;) between statements. The JS parser will decide whether to automatically fill in the semicolon based on whether it can be compiled normally:
var test = 1 + 2console.log(test); //3
In the above In this case, in order to correctly parse the code, the semicolon will not be automatically filled in. However, for return, break, continue and other statements, if it is followed by a newline, the parser will automatically fill in the semicolon (;) at the end, so the above The second function becomes like this:
function foo2(){return;{bar: "hello"};}
So the second function returns undefined.
7. Shenma is NaN, and its type is Shenma? How to test whether a value is equal to NaN?
NaN is the abbreviation of Not a Number, a special numerical value in JavaScript. Its type is Number. You can use isNaN(param) to determine whether a value is NaN:
console.log(isNaN(NaN)); //trueconsole.log(isNaN(23)); //falseconsole.log(isNaN('ds')); //trueconsole.log(isNaN('32131sdasd')); //trueconsole.log(NaN === NaN); //falseconsole.log(NaN === undefined); //falseconsole.log(undefined === undefined); //falseconsole.log(typeof NaN); //numberconsole.log(Object.prototype.toString.call(NaN)); //[object Number]ES6 中,isNaN() 成为了 Number 的静态方法:Number.isNaN().
8. Explain the output of the following code
console.log(0.1 + 0.2); //0.30000000000000004console.log(0.1 + 0.2 == 0.3); //false
The number type in JavaScript is floating point. The floating point number in JavaScript adopts the IEEE-754 format, which is a binary representation. , can accurately represent fractions, such as 1/2, 1/8, 1/1024, each floating point number occupies 64 bits. However, binary floating point number representation cannot accurately represent simple numbers like 0.1, and there will be rounding errors.
Due to the use of binary, JavaScript cannot limitly represent fractions such as 1/10, 1/2, etc. In binary, 1/10 (0.1) is represented as 0.00110011001100110011... Note that 0011 is repeated infinitely, which is caused by rounding errors, so for operations such as 0.1 + 0.2, the operands will first be converted into binary, and then Recalculate:
0.1 => 0.0001 1001 1001 1001… (infinite loop)
0.2 => 0.0011 0011 0011 0011… (infinite loop)
Decimal of double precision floating point number Part supports up to 52 bits, so after adding the two, we get a string of 0.0100110011001100110011001100110011001100... A binary number that is truncated due to the limitation of decimal places in floating point numbers. At this time, convert it to decimal and it becomes 0.30000000000000004.
对于保证浮点数计算的正确性,有两种常见方式。
一是先升幂再降幂:
function add(num1, num2){ let r1, r2, m; r1 = (''+num1).split('.')[1].length; r2 = (''+num2).split('.')[1].length; m = Math.pow(10,Math.max(r1,r2)); return (num1 * m + num2 * m) / m;}console.log(add(0.1,0.2)); //0.3console.log(add(0.15,0.2256)); //0.3756
二是是使用内置的 toPrecision() 和 toFixed() 方法,注意,方法的返回值字符串。
function add(x, y) { return x.toPrecision() + y.toPrecision()}console.log(add(0.1,0.2)); //"0.10.2"
9、实现函数 isInteger(x) 来判断 x 是否是整数
可以将 x 转换成10进制,判断和本身是不是相等即可:
function isInteger(x) { return parseInt(x, 10) === x; }
ES6 对数值进行了扩展,提供了静态方法 isInteger() 来判断参数是否是整数:
Number.isInteger(25) // trueNumber.isInteger(25.0) // trueNumber.isInteger(25.1) // falseNumber.isInteger("15") // falseNumber.isInteger(true) // false
JavaScript能够准确表示的整数范围在 -2^53 到 2^53 之间(不含两个端点),超过这个范围,无法精确表示这个值。ES6 引入了Number.MAX_SAFE_INTEGER 和 Number.MIN_SAFE_INTEGER这两个常量,用来表示这个范围的上下限,并提供了 Number.isSafeInteger() 来判断整数是否是安全型整数。
10、在下面的代码中,数字 1-4 会以什么顺序输出?为什么会这样输出?
(function() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4);})();
这个就不多解释了,主要是 JavaScript 的定时机制和时间循环,不要忘了,JavaScript 是单线程的。
11、写一个少于 80 字符的函数,判断一个字符串是不是回文字符串
function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return (str == str.split('').reverse().join(''));}
12、写一个按照下面方式调用都能正常工作的 sum 方法
console.log(sum(2,3)); // Outputs 5console.log(sum(2)(3)); // Outputs 5
针对这个题,可以判断参数个数来实现:
function sum() {var fir = arguments[0];if(arguments.length === 2) {return arguments[0] + arguments[1]} else {return function(sec) {return fir + sec;}}}
13、下面的代码会输出什么?为什么?
var arr1 = "john".split(''); j o h nvar arr2 = arr1.reverse(); n h o jvar arr3 = "jones".split(''); 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));
会输出什么呢?你运行下就知道了,可能会在你的意料之外。
MDN 上对于 reverse() 的描述是酱紫的:
>DescriptionThe reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.>reverse()
会改变数组本身,并返回原数组的引用。>slice 的用法请参考:slice
14、下面的代码会输出什么?为什么?
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);
输出什么,自己去运行吧,需要注意三个点:
多个数字和数字字符串混合运算时,跟操作数的位置有关
console.log(2 + 1 + '3'); / /‘33’console.log('3' + 2 + 1); //'321'
数字字符串之前存在数字中的正负号(+/-)时,会被转换成数字
console.log(typeof '3'); // stringconsole.log(typeof +'3'); //number
同样,可以在数字前添加 '',将数字转为字符串
console.log(typeof 3); // numberconsole.log(typeof (''+3)); //string
对于运算结果不能转换成数字的,将返回 NaN
console.log('a' * 'sd'); //NaNconsole.log('A' - 'B'); // NaN
这张图是运算转换的规则
15、如果 list 很大,下面的这段递归代码会造成堆栈溢出。如果在不改变递归模式的前提下修善这段代码?
var list = readHugeList();var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... nextListItem(); }};
原文上的解决方式是加个定时器:
var list = readHugeList();var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... setTimeout( nextListItem, 0); }};
解决方式的原理请参考第10题。
16、什么是闭包?举例说明
可以参考此篇:从作用域链谈闭包(去看看)
17、下面的代码会输出什么?为啥?
for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 );}
请往前面翻,参考第4题,解决方式已经在上面了
18、解释下列代码的输出
console.log("0 || 1 = "+(0 || 1));console.log("1 || 2 = "+(1 || 2));console.log("0 && 1 = "+(0 && 1));console.log("1 && 2 = "+(1 && 2));
逻辑与和逻辑或运算符会返回一个值,并且二者都是短路运算符:
逻辑与返回第一个是 false 的操作数 或者 最后一个是 true的操作数
console.log(1 && 2 && 0); //0console.log(1 && 0 && 1); //0console.log(1 && 2 && 3); //3
如果某个操作数为 false,则该操作数之后的操作数都不会被计算
逻辑或返回第一个是 true 的操作数 或者 最后一个是 false的操作数
console.log(1 || 2 || 0); //1console.log(0 || 2 || 1); //2console.log(0 || 0 || false); //false
如果某个操作数为 true,则该操作数之后的操作数都不会被计算
如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高:
console.log(1 && 2 || 0); //2console.log(0 || 2 && 1); //1console.log(0 && 2 || 1); //1
在 JavaScript,常见的 false 值:
0, '0', +0, -0, false, '',null,undefined,null,NaN
要注意空数组([])和空对象({}):
console.log([] == false) //trueconsole.log({} == false) //falseconsole.log(Boolean([])) //trueconsole.log(Boolean({})) //true
所以在 if 中,[] 和 {} 都表现为 true:
19、解释下面代码的输出
console.log(false == '0')console.log(false === '0')请参考前面第14题运算符转换规则的图。
20、解释下面代码的输出
var a={}, b={key:'b'}, c={key:'c'};a[b]=123;a[c]=456;console.log(a[b]);
输出是 456,参考原文的解释:
The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]". As a result, a[b] anda[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].
21、解释下面代码的输出
console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));
结果是10的阶乘。这是一个递归调用,为了简化,我初始化 n=5,则调用链和返回链如下:
22、解释下面代码的输出
(function(x) { return (function(y) { console.log(x); })(2)})(1);
输出1,闭包能够访问外部作用域的变量或参数。
23、解释下面代码的输出,并修复存在的问题
var hero = { _name: 'John Doe', getSecretIdentity: function (){ return this._name; }}; var stoleSecretIdentity = hero.getSecretIdentity;console.log(stoleSecretIdentity());console.log(hero.getSecretIdentity()); 将 getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数: var stoleSecretIdentity = function (){return this._name;}
stoleSecretIdentity 的上下文是全局环境,所以第一个输出 undefined。若要输出 John Doe,则要通过 call 、apply 和 bind 等方式改变 stoleSecretIdentity 的this 指向(hero)。
第二个是调用对象的方法,输出 John Doe。
24、给你一个 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 }}
以上就是24个JavaScript的面试题,不管你是不是准备要出去找工作了,我相信这一套题目对大家都很有帮助。
相关推荐:
关于javascript常见面试题_javascript技巧
The above is the detailed content of 24 JavaScript interview questions. For more information, please follow other related articles on the PHP Chinese website!