Summary of 86 interview questions based on Javascript (with answers)

1. What kind of language is JavaScript and what are its characteristics? (no standard answer)

Reference answer:
JavaScript is a powerful programming language, a scripting language designed for interacting with web pages, and a dynamically typed, weakly typed, prototype-based language.

JavaScript is a client-side and server-side scripting language that can be inserted into HTML pages and is currently the most popular language for web development. At the same time, JavaScript is also an object-oriented programming language.

Features :

1. Scripting language. JavaScript is an interpreted scripting language. C, C++ and other languages ​​are compiled first and then executed, while JavaScript is interpreted line by line during the running of the program.
2. Object-based. JavaScript is an object-based scripting language, it can not only create objects, but also use existing objects.
3. Simple. The JavaScript language uses weakly typed variable types, and does not make strict requirements on the data types used. It is a scripting language based on Java basic statements and controls, and its design is simple and compact.
4. Dynamic. JavaScript is an event-driven scripting language, which can respond to user input without going through a Web server. When visiting a web page, JavaScript can directly respond to these events when the mouse is clicked or moved up and down in the web page, or the window is moved.
5. Cross-platform. The JavaScript scripting language does not depend on the operating system, only needs the support of the browser. Therefore, a JavaScript script can be used on any machine after being written, provided that the browser on the machine supports the JavaScript scripting language, JavaScript has been supported by most browsers at present.

2. What are the data types of JavaScript?

  • Basic data types: Number, String, Boolean, Null, Undefined
  • Complex data types: Object (Function, Array, Date, RegExp)

How to judge whether a variable is an array data type?

if (typeof Array.isArray === "undefined"){
	Array.isArray = function(arg){
		return Object.prototype.toString.call(arg)==="[object Array]";
	}
}

3. If you want to get the input value of an input box with a known ID, how do you do it? (does not use third-party frameworks)

document.getElementById(ID).value;

4. How do you want to get all the checkboxes on the page? (does not use third-party frameworks)

var inputs = document.getElementsByTagName("input"),
	arr = [],
	len = inputs.length;
while (len--){
	if(inputs[len].type == "checkbox"){
		arr.push(inputs[i]);
	}
}

5. Set the html content of a DIV with a known ID to xxxx, and set the font color to black (without using a third-party framework)

var oDiv = document.getElementById(ID);
oDiv.innerHTML = "xxxx";
oDiv.getElementById(ID).style.color = "black";

6. When a DOM node is clicked, we want to execute a function, what should we do?

First get the DOM node, and then bind the onclick event. such as myDOM.onclick = fnormyDOM.addEventListener("click",fn);

or bind directly in HTML<div onclick = "fn()"></div>

7. What are Ajax and JSON, their pros and cons.

Ajax is asynchronous JavaScript and XML for asynchronous data interaction in web pages.

advantage:

  • It can make the page load partial content without reloading all the content, reducing the amount of data transmission
  • Prevent users from constantly refreshing or jumping pages to improve user experience

shortcoming:

  • Not friendly to search engines
  • It is costly to realize the forward and backward functions under ajax
  • May cause an increase in the number of requests
  • Limitations on Cross-Origin Issues

JSON is a lightweight data interchange format, a subset of ECMA

Advantages: Lightweight, easy to read and write for humans, easy for machine (JavaScript) parsing, support for composite data types (arrays, objects, strings, numbers)

8. What is the output of the following code? explain the reason.

var a;
alert(typeof a); //undefined
alert(b); //报错

The variable a is declared, but it is not assigned a value, so the value is undefined. And b is not declared, so it does not exist.

9. Look at the following code, what is the output? explain the reason.

var a = null;
alert(typeof a); //object

10. Look at the following code, what is the output? explain the reason.

var undefined;
undefined == null; //true
1 == true; //true
2 == true; //false
0 == false; //true
0 == ''; // true
NaN == NaN; //false
[] == false; //true
[] == ![]; //true
  • undefined and null will be automatically converted to false in the if statement, and the equality operator directly reports that the two are equal. (If it is congruent, the result is false)
  • Comparing a number to a boolean will turn the boolean into a number, 1 for true and 0 for false.
  • 0 is false that is false, empty value or space is also false.
  • NaN is not equal to any value.
  • [] is treated as an array, and an empty array is converted to 0, so it is equal to false.
  • ![] wants to do the operation of converting an array to a Boolean value, [] is an array object, so ![] is false.

Look at the code below, what is the output, what is the value of foo?

var foo = "11"+2-"1";
console.log(foo); //111

First do the "11"+2 operation. When one is a string and the other is a number, convert the number to a string, so the strings are concatenated into "112". When both data are strings, operations other than + will first convert the strings to numbers, that is, 112-1=111, and the type of foo is Number. If it is a + operation, it is "112"+"1"="1121", and the type of foo is String.

11. Look at the code to give the answer.

var a = new Object();
a.value = 1;
b = a;
b.value = 2;
alert(a.value); //2

a and b both point to the same object, so b modifies the value, and the value of a also changes.

12. Known array var stringArray = [“This”, “is”, “Baidu”, “Campus”], Alert will display "This is Baidu Campus".

stringArray.join(" ");

It is known that there is a string foo="get-element-by-id", write a function to convert it into camelcase notation "getElementById".

var fooArr = foo.split("-");
var newFoo = fooArr[0];
for(var i=1;i<fooArr.length;i++){
	newFoo += fooArr[i].charAt(0).toUpperCase()+fooArr[i].slice(1);
}
return newFoo;

13.var numberArray = [3,6,2,4,1,5];

  1. Realize the inversion of the array, output [5,1,4,2,6,3]

    numberArray.reverse();

  2. Realize the descending order of the array, output [6,5,4,3,2,1]

numberArray.sort(function(a,b){
   	return b-a;
   });

14. Output today's date in the form of YYYY-MM-DD, for example, if today is September 26, 2014, then output 2014-09-26

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var nowDate = date.getDate();
if(month<10){month = "0" + month;}
if(nowDate<10){nowDate = "0" + nowDate;}
var today = year + "-" + month + "-" + nowDate;

15. Put the string "<tr><td>{KaTeX parse error: Expected 'EOF', got '}' at position 3: id}̲</td><…name}</td></tr> In "{KaTeX parse error: Expected 'EOF', got '}' at position 3: id}̲ is replaced with 10, and {name} is replaced with Tony. (using regular expressions)

var str = "<tr><td>{$id}</td><td>{$name}</td></tr>";
str.replace(/\{\$id\}/,"10").replace(/\{\$name\}/,"Tony");

16. In order to ensure the safety of page output, we often need to escape some special characters, please write a function escapeHtml to escape <, >, &, \

function escapeHTML(str){
	return str.replace(/[<>&"]/g,function(match){
		switch(match){
			case "<":
			return "\<";
			case ">":
			return "\>";
			case "&":
			return "\&";
			case "\"":
			return "\"";
		}
	});
}

17. foo = foo||bar , what does this line of code mean? Why do you write like this?

If foo is not false, the original value is used, and if there is no value, the value of bar is paid to foo.

18. Look at the following code, what will be output? (variable declaration promotion)

var foo = 1;
function(){
	console.log(foo); //undefined
	var foo = 2;
	console.log(foo); //2
}

Function declarations and variable declarations are implicitly hoisted to the top of the current scope, but assignments are not hoisted. Equivalent to:

var foo = 1;
function(){
	var foo;
	console.log(foo); //undefined
	foo = 2;
	console.log(foo); //2
}

19. Use js to randomly select 10 numbers between 10-100, store them in an array, and sort them.

var url = "http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e";
var gets = url.split("?")[1];
var getsArr = gets.split("&");
var obj = {};
for(var i=0;i<getsArr.length;i++){
	obj[getsArr[i].split("=")[0]] = getsArr[i].split("=")[1];
}
return obj;

20. Merge the two arrays and delete the second element.

var arr1 = [1,2,3];
var arr2 = [“a”,“b”,“c”];
var newArr = arr1.current(arr2);
newArr.splice(1,1);

21. How to add, remove, move, copy, create and find nodes

- appendChild() //添加
- reomveChild() //移除
- insertBefore() //移动
- cloneNode() //复制
- createElement();createTextNode();createDocumentFragment //复制
- getElementById();getElementsByTagName();getElementsByClassName();getElementsByName() //查找

22. There is such a URL: http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e, please write a JS program to extract each GET parameter in the URL (the parameter name and the number of parameters are different OK), return it to a json structure in the form of key-value, such as {a:'1', b:'2', c:", d:'xxx', e:undefined}

var url = "http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e";
var gets = url.split("?")[1];
var getsArr = gets.split("&");
var obj = {};
for(var i=0;i<getsArr.length;i++){
	obj[getsArr[i].split("=")[0]] = getsArr[i].split("=")[1];
}
return obj;

23. What is the difference between the regular expression constructor var reg=new RegExp("xxx") and the regular expression literal var reg=//? Regular expression to match mailboxes?

When using the RegExp() constructor, not only do you need to escape the quotes (that is, "for"), but you also need double backslashes (that is, \ for a \).

/^([A-Za-z0-9-_])+@([A-Za-z0-9]+.)+([a-z])+$/

24. Look at the following code and give the output result.

for(var i=1;i<=3;i++){
  setTimeout(function(){
  console.log(i); //4 //4 //4
  },0);  
};

Javascript event handlers won't run until the thread is free.

How to make the above code output 1 2 3?

for(var i=1;i<=3;i++){
  setTimeout((function(i){
  console.log(i);
  })(i),0);  //立即执行函数
};

25. Write a function to clear the spaces before and after the string. (compatible with all browsers)

if(!String.prototype.trim){
	String.prototype.trim = function(){
		return this.replace(/^\s+/,"").replace(/\s+$/,"");
	}
}

26. What are the functions of callee and caller in Javascript?

If a pair of rabbits gives birth to a pair of rabbits every month; a pair of newborn rabbits will start to give birth to rabbits from the third month; assuming that each pair of rabbits is a female and a male, how many can a pair of rabbits reproduce in the nth month? To the rabbit? (done using callee)

var result = [];
function fn(n){
	if(n==1){
		return 1;
	}else if(n==2){
		return 1;
	}else{
		result[n] = arguments.callee(n-2)+arguments.callee(n-1);
		return result[n];
	}
}

27. Explain what a callback function is and provide a simple example

A callback function is a function that can be passed as an argument to another function and executed after some action is complete. Below is an example of a simple callback function that prints a message to the console after some operation is complete.

function modifyArray(arr, callback) {
 // 对 arr 做一些操作
 arr.push(100);
 // 执行传进来的 callback 函数
 callback();
}
var arr = [1, 2, 3, 4, 5];
modifyArray(arr, function() {
 console.log("array has been modified", arr);
});

28. How to check if a number is an integer?

A very simple way to check whether a number is a decimal or an integer is to take it modulo 1 and see if there is a remainder.

function isInt(num) {
 return num % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false

29. Can you explain the difference between ES5 and ES6?

ECMAScript 5 (ES5): The fifth edition of ECMAScript, standardized in 2009. This standard is fully implemented in all modern browsers.
ECMAScript 6 (ES6) or ECMAScript 2015 (ES2015): The 6th edition of ECMAScript, standardized in 2015. This standard is partially implemented in most modern browsers.
Here are some key differences between ES5 and ES6:
 

// 箭头函数和字符串插值:
const greetings = (name) => {
 return `hello ${name}`;
}
const greetings = name => `hello ${name}`;

30. What is a "closure" in Javascript? for example?

A closure is a function defined inside another function (called a parent function) and has access to variables declared and defined in the parent function's scope.

Closures can access variables in three scopes:

  • Variables declared in their own scope;
  • variables declared in the parent function;
  • Variables declared in the global scope.
    var globalVar = "abc";
    // 自调用函数
    (function outerFunction (outerArg) { // outerFunction 作用域开始
     // 在 outerFunction 函数作用域中声明的变量
     var outerFuncVar = 'x'; 
     // 闭包自调用函数
     (function innerFunction (innerArg) { // innerFunction 作用域开始
     // 在 innerFunction 函数作用域中声明的变量
     var innerFuncVar = "y";
     console.log( 
     "outerArg = " + outerArg + "
    " +
     "outerFuncVar = " + outerFuncVar + "
    " +
     "innerArg = " + innerArg + "
    " +
     "innerFuncVar = " + innerFuncVar + "
    " +
     "globalVar = " + globalVar);
     // innerFunction 作用域结束
     })(5); // 将 5 作为参数
    // outerFunction 作用域结束
    })(7); // 将 7 作为参数
    

    innerFunction is a closure defined within outerFunction and has access to all variables declared and defined within the scope of outerFunction. In addition to this, closures can also access variables declared in the global namespace.

    The output of the above code will be:

    outerArg = 7
    outerFuncVar = x
    innerArg = 5
    innerFuncVar = y
    globalVar = abc
    

    31. What is the rationale for the "this" keyword? Please provide some code samples.

  • In JavaScript, this refers to the "owner" of the function being executed, or more precisely, the object that has the current function as a method.
    function foo() {
     console.log( this.bar );
    }
    var bar = "global";
    var obj1 = {
     bar: "obj1",
     foo: foo
    };
    var obj2 = {
     bar: "obj2"
    };
    foo(); // "global"
    obj1.foo(); // "obj1"
    foo.call( obj2 ); // "obj2"
    new foo(); // undefined
    

    32. How to add a custom method to the Array object so that the following code can run?

JavaScript is not class-based, but it is a prototype-based language. This means that each object is linked to another object (that is, the object's prototype), and inherits the methods of the prototype object. You can follow each object's prototype chain until you reach a null object with no prototype. We need to add methods to the global Array object by modifying the Array prototype.

Array.prototype.average = function() {
 // 计算 sum 的值
 var sum = this.reduce(function(prev, cur) { return prev + cur; });
 // 将 sum 除以元素个数并返回
 return sum / this.length;
}
var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg); // => 3

33. Please describe the Revealing Module Pattern design pattern.

The Revealing Module Pattern is a variant of the Module Pattern that aims to maintain encapsulation and expose certain variables and methods returned in objects. As follows:

var Exposer = (function() {
 var privateVariable = 10;
 var privateMethod = function() {
 console.log('Inside a private method!');
 privateVariable++;
 }
 var methodToExpose = function() {
 console.log('This is a method I want to expose!');
 }
 var otherMethodIWantToExpose = function() {
 privateMethod();
 }
 return {
 first: methodToExpose,
 second: otherMethodIWantToExpose
 };
})();
Exposer.first(); // 输出: This is a method I want to expose!
Exposer.second(); // 输出: Inside a private method!
Exposer.methodToExpose; // undefined

One of its obvious disadvantages is the inability to reference private methods.

34. List the differences between Java and JavaScript?

Java is a very complete and mature programming language. In contrast, JavaScript is a programming language that can be introduced into HTML pages. The two languages ​​are not exactly dependent on each other, but are designed for different purposes. Java is an object-oriented programming (OOPS) or structured programming language, similar like C++ or C, while JavaScript is a client-side scripting language, which is known as unstructured programming.


35. What data types does javascript's typeof return?

答案:string,boolean,number,undefined,function,object,symbol

36. Give examples of 3 mandatory type conversions and 2 implicit type conversions?

Answer: coerce(parseInt, parseFloat, number)
implicit(=====)

37. What is the difference between split() and join()?

Answer: The former is to cut the string into an array, and the latter is to convert the array into a string

38. The difference between the array method pop() push() unshift() shift()?

Answer: push() tail add pop() tail delete
unshift() head add shift() head delete

39. What are the compatible writing methods under IE and the standard?

var ev = ev || window.event
document.documentElement.clientWidth || document.body.clientWidth
Var target = ev.srcElement||ev.target

40. What is the difference between get and post when making ajax requests?

Answer:
One is behind the url, and the other is placed in the virtual carrier.
Get has a size limit (only a small number of parameters can be submitted).
Security issues
Different applications, request data and submit data

41. What is the difference between call and apply?

Object.call(this,obj1,obj2,obj3)
Object.apply(this,arguments)

42. How to parse json data during ajax request?

Answer: use JSON.parse

44. What is event delegation?

Answer: Use the principle of event bubbling to let your own triggered event be executed by its parent element instead!

45. What is a closure, what are its characteristics, and what impact does it have on the page?

Answer: A closure is a function that can read the internal variables of other functions, so that the function will not be recycled by the GC. If you use too many closures, it will easily lead to memory leaks

おすすめ

転載: blog.csdn.net/w199809w/article/details/128562574