Home >Web Front-end >JS Tutorial >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
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]
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'));
This is related to the variable scope. The output is changed to the following:
console.log(b); //3 console,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. 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); }());
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));
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); }
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) }
In the development of JQuery/Node plug-ins and modules, in order to avoid variable pollution, it is also a big IIFE:
(function($) { //代码 } )(jQuery);
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 = (''+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.3 console.log(add(0.15,0.2256)); //0.3756
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"
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; }
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
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); })();
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, '').toLowerCase(); return (str == str.split('').reverse().join('')); }
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
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; } } }
11. Answer the following questions based on the code snippet below
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); }); document.body.appendChild(btn); }
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(''); j o h n var arr2 = arr1.reverse(); n h o j var 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));
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);
输出什么,自己去运行吧,需要注意三个点:
多个数字和数字字符串混合运算时,跟操作数的位置有关
console.log(2 + 1 + '3'); / /‘33' console.log('3' + 2 + 1); //'321'
数字字符串之前存在数字中的正负号(+/-)时,会被转换成数字
console.log(typeof '3'); // string console.log(typeof +'3'); //number
同样,可以在数字前添加 '',将数字转为字符串
console.log(typeof 3); // number console.log(typeof (''+3)); //string
对于运算结果不能转换成数字的,将返回 NaN
console.log('a' * 'sd'); //NaN console.log('A' - 'B'); // NaN
14、什么是闭包?举例说明
可以参考此篇:从作用域链谈闭包
15、下面的代码会输出什么?为啥?
for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }
请往前面翻,参考第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));
逻辑与和逻辑或运算符会返回一个值,并且二者都是短路运算符:
逻辑与返回第一个是 false 的操作数 或者 最后一个是 true的操作数
console.log(1 && 2 && 0); //0 console.log(1 && 0 && 1); //0 console.log(1 && 2 && 3); //3
如果某个操作数为 false,则该操作数之后的操作数都不会被计算
逻辑或返回第一个是 true 的操作数 或者 最后一个是 false的操作数
console.log(1 || 2 || 0); //1 console.log(0 || 2 || 1); //2 console.log(0 || 0 || false); //false
如果某个操作数为 true,则该操作数之后的操作数都不会被计算
如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高:
console.log(1 && 2 || 0); //2 console.log(0 || 2 && 1); //1 console.log(0 && 2 || 1); //1
在 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
所以在 if 中,[] 和 {} 都表现为 true:
17、解释下面代码的输出
console.log(false == '0') console.log(false === '0')
18、解释下面代码的输出
var a={}, b={key:'b'}, c={key:'c'}; a[b]=123; a[c]=456; console.log(a[b]); 输出是456。
19、在下面的代码中,数字 1-4 会以什么顺序输出?为什么会这样输出?
(function() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4); })();
这个就不多解释了,主要是 JavaScript 的定时机制和时间循环,不要忘了,JavaScript 是单线程的。详解可以参考 从setTimeout谈JavaScript运行机制。
20、写一个少于 80 字符的函数,判断一个字符串是不是回文字符串
function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return (str == str.split('').reverse().join('')); }
这个题我在 codewars 上碰到过,并收录了一些不错的解决方式,可以戳这里:Palindrome For Your Dome
21、写一个按照下面方式调用都能正常工作的 sum 方法
console.log(sum(2,3)); // Outputs 5 console.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; } } }
22、解释下面代码的输出,并修复存在的问题
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。
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 } }
相关学习推荐:javascript视频教程