JavaScript interview questions you must know

JavaScript Art 2021-06-17 18:18:16
javascript interview questions know


javascript Interview questions you must know

1、 Use typeof bar === "object" Judge bar Is it a potential disadvantage of a target ? How to avoid this kind of malpractice ?

Use typeof The malpractice is obvious ( This kind of malpractice 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, we can see that ,typeof bar === "object" It's not accurate to judge bar It's just one. Object. Can pass Object.prototype.toString.call(bar) === "[object Object]" To avoid this kind of malpractice :

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 , To cherish life , Please stay away ==: Cherish life,

and [] === false Is to return false Of .

2、 The following code will be in console Export Shenma ? Why? ?

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

It's about variable scope , Change the output to the following :

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

Take apart the variable assignment in the self executing function :

b = 3;var a = b;

therefore b It becomes a global variable , and a Is a local variable of a self executing function .

3、 The following code will be in console Export Shenma ? 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 output of the first and the second is not difficult to judge , stay ES6 Before ,JavaScript Only function scope , therefore func Medium IIFE It has its own independent scope , And it has access to self, So the third output will report an error , because this Within the accessible scope is undefined, The fourth output is bar. If you know closures , It's 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're not familiar with closures , You can poke this : From scope chain to closure

4、 take JavaScript Code contained in a function block has the meaning of god horse ? Why do you do this ?

let me put it another way , Why use immediate execution function expressions (Immediately-Invoked Function Expression).

IIFE There are two classic scenarios , One is similar to outputting data items in a loop , Second, it is similar to JQuery/Node Plug in and module development of .

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

The output above is not what you think 0,1,2,3,4, And all the output is 5, At this time IIFE It's going to work :

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

And in the JQuery/Node In the development of plug-ins and modules , To avoid variable contamination , It's also a big IIFE:

(function($) {
// Code
} )(jQuery);

5、 In strict mode ('use strict') Proceed under JavaScript Development is good for Shenma ?

eliminate Javascript Some unreasonable grammar 、 Not rigorous , Reduce some weird behavior ; Eliminate some insecurity of code running , Ensure the safety of code operation ; Improve compiler efficiency , Increase running speed ; For future new versions of Javascript Pave the way .

6、 Is the return value of the following two functions the same ? Why? ?

function foo1(){ return {
bar: "hello"
};
}function foo2(){ return
{
bar: "hello"
};
}

In programming languages , They basically use semicolons (;) Separate statements , This can increase the readability and neatness of the code . And in the JS in , If each sentence occupies a separate line , You can usually omit semicolons between statements (;),JS The parser will decide whether to automatically fill the semicolon according to whether it compiles normally :

var test = 1 + 2;console.log(test); //3

In the above case , In order to parse the code correctly , You don't automatically fill in semicolons , But for return 、break、continue Such statements , If it's followed by a line break , The parser must automatically fill in the semicolon after it (;), So the second function above goes like this :

function foo2(){ return;
{
bar: "hello"
};
}

So the second function is to return undefined.

7、 What is god horse? NaN, Its type is Shenma ? How to test whether a value is equal to NaN?

NaN yes Not a Number Abbreviation ,JavaScript A special numerical value of , The type is Number, Can pass 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 in ,isNaN() Become Number Static method of :Number.isNaN().

8、 Explain the output of the following code

console.log(0.1 + 0.2);
//0.30000000000000004
console.log(0.1 + 0.2 == 0.3);
//false

JavaScript Medium number The type is floating point ,JavaScript The floating-point number in is IEEE-754 The rules of the form , This is a binary representation , It can express the score exactly , such as 1/2,1/8,1/1024, Each floating-point number accounts for 64 position . however , Binary floating-point representation is not exactly similar to 0.1 such A simple number of , There will be rounding errors .

Because of the binary system ,JavaScript It can't be limited to 1/10、1/2 Wait for a score like this . In binary ,1/10(0.1) Expressed as 0.00110011001100110011…… Be careful 0011 It's infinite repetition , This is caused by rounding error , So for 0.1 + 0.2 Operations like this , The operands are first converted to binary , And then calculate :

0.1 => 0.0001 1001 1001 1001…( Infinite loop )
0.2 => 0.0011 0011 0011 0011…( Infinite loop )

The decimal part of double precision floating-point numbers supports at most 52 position , So the two add up to get this string 0.0100110011001100110011001100110011001100... A binary number truncated due to the limitation of decimal places in floating point numbers , Now , And convert it to decimal , became 0.30000000000000004.

For ensuring the correctness of floating point number calculation , There are two common ways :

One is to raise the power first and then lower it :

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() Method , Be careful , 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"

9、 Implementation function isInteger(x) To judge x Is it an integer

Can be x convert to 10 Base number , Judge whether it is equal to itself :

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

ES6 The numerical value is extended , Provides a static method isInteger() To determine whether the parameter is an integer :

Number.isInteger(25) // trueNumber.isInteger(25.0) // trueNumber.isInteger(25.1) // falseNumber.isInteger("15") // falseNumber.isInteger(true) // false

JavaScript The range of integers that can be expressed accurately is -2^53 To 2^53 Between ( Without two endpoints ), Beyond that range , It's impossible to express the value exactly .ES6 Introduced Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER These two constants , Used to indicate the upper and lower limits of this range , And provides Number.isSafeInteger() To determine whether an integer is a safe integer .

10、 In the following code , Numbers 1-4 In what order will it be output ? Why does this output ?

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

I don't want to explain that much , Mainly JavaScript The timing mechanism and time cycle of , Don't forget to ,JavaScript It's single threaded . Please refer to from setTimeout To talk about JavaScript Operating mechanism .

11、 Write a less than 80 Character functions , Determine whether a string is palindrome string

function isPalindrome(str) {
str = str.replace(/\W/g, '').toLowerCase();
return (str == str.split('').reverse().join(''));
}

This question I am in codewars I've come across , And included some good solutions , You can poke it here :Palindrome For Your Dome

12、 Write a call that works in the following way sum Method

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

For this problem , It can be realized 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;
}
}}

13、 Answer the following questions according to the following code snippet

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 on Button 4, What will be output on the console ? 2、 Give a way to achieve the expected

answer :1、 Click on 5 Any one of the buttons , It's all output 5

14、 What the following code will 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 sarr2.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's going to be output ? You'll know when you run it , It might be unexpected .

reverse() It changes the array itself , And return the reference of the original array .

15、 What the following code will 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);

What output , Run it yourself , Three points need to be noted :

1、 When multiple numbers and numeric strings are mixed , It depends on the position of the operands

console.log(2 + 1 + '3'); / /‘33’
console.log('3' + 2 + 1); //'321'

A number string is preceded by a sign in the number (+/-) when , It's going to be converted into numbers

console.log(typeof '3'); // string
console.log(typeof +'3'); //number

Again , You can add... Before the number '', Convert a number to a string .

2、

console.log(typeof 3); // number
console.log(typeof (''+3)); //string

The result of the operation can not be converted into a number , Will return NaN

console.log('a' * 'sd'); //NaN
console.log('A' - 'B'); // NaN

3、 Operator conversion

16、 If list It's big , The following recursive code will cause a stack overflow . If you fix this code without changing the recursive mode ?

var list = readHugeList();var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
nextListItem();
}
};

The original solution is to add a timer :

var list = readHugeList();var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
setTimeout( nextListItem, 0);
}
};

For the principle of the solution, please refer to section 10 topic .

17、 What is a closure ? Illustrate with examples

You can refer to this article : From scope chain to closure

18、 What the following code will output ? Why? ?

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

Please turn to the front , Refer to the first 4 topic , The solution is already there

19、 Explain the output of the following code

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

The logical and and logical or operator returns a value , And both are short circuit operators :

Logic and return the first is false The number of operations perhaps The last one is true The number of operations

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

If one of the operands is false, Then the operands after the operands will not be calculated

The first logical or return is true The number of operations perhaps The last one is false The number of operations

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

If one of the operands is true, Then the operands after the operands will not be calculated

If logic and sum logic or do mixed operations , The priority of logical and is high :

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

stay JavaScript, common false value :

Pay attention to empty arrays ([]) And empty objects ({}):

console.log([] == false) //true
console.log({} == false) //falseconsole.log(Boolean([])) //true
console.log(Boolean({})) //true

So in if in ,[] and {} Are characterized by true:

20、 Explain the output of the following code

console.log(false == '0')
console.log(false === '0')

Please refer to the previous section 14 The graph of the conversion rules of question operators .

21、 Explain the output of the following code

var a={},
b={key:'b'},
c={key:'c'};a[b]=123;
a[c]=456;console.log(a[b]);

The output is 456, Refer to the original explanation :

22、 Explain the output of the following code

console.log((function f(n){
return ((n > 1) ? n * f(n-1) : n)}
)(10));

The result is 10 The factorial . This is a recursive call , In order to simplify the , I initialize n=5, The call chain and return chain are as follows :

recursive

23、 Explain the output of the following code

(function(x) {
return (function(y) {
console.log(x);
})(2)
})(1);

Output 1, Closures can access variables or parameters of an external scope .

24、 Explain the output of the following code , And fix the problems

var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};
var stoleSecretIdentity = hero.getSecretIdentity;
console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());

take getSecretIdentity Assign to stoleSecretIdentity, It's equivalent to defining stoleSecretIdentity function :

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

stoleSecretIdentity The context is the global environment , So the first output undefined. To output John Doe, Then through call 、apply and bind And so on stoleSecretIdentity Of this Point to (hero).

The second is to call the method of the object , Output John Doe.

25、 To give you one DOM Elements , Create a function that can access all the child elements of the element , And pass each child element to the specified callback function .

The function takes two arguments :

DOM The specified callback function The original text uses Depth-first search (Depth-First-Search) Gives an implementation :

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
}
}

Reprint to blog http://www.cnblogs.com/dushao/p/5999557.htm

When we were young and stuck to something we thought was right , There are always some elders , It's all out of kindness , Come to remind you , Tell you that this society is not like what you think , If you want to do something , It has to be . Have you heard that many times ? I've heard that all the time since I grew up , I never listen to , I've always insisted on what I thought was right when I was young .—— Mr Luo

This article is from WeChat official account. - javascript art (gh_4e5484fd6b52) , author : Du Shao blog

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2018-02-28

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[JavaScript Art]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210528141722990z.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless