[high frequency written interview in front-end field] - JavaScript related

catalogue

1. Write a regular expression that simply describes the html tag (start tag and end tag without attributes), and remove the html tag from the string

2. Complete the function showImg(), which requires that the display of the picture can be updated dynamically according to the options in the drop-down list

3. List the common objects in the browser object model BOM and the common methods of window objects

4. List the common methods to find and access nodes of document in the Document Object Model DOM

5. What should I do if I want to get all the checkbox es in the page

6. Briefly describe several ways to create functions

7. How does JavaScript implement inheritance?

8. Several ways of JavaScript creating objects

9. Advantages and disadvantages of iframe

10. Please talk about the disadvantages of cookies

11. What are the ways to delay the loading of JS?

12. What is the difference between document.write and innerHTML?

13. What operations will cause memory leakage?

14. Judge the character that appears the most times in a string and count the times

15. What is the event delegation?

16. What are closures, what are their characteristics, and what impact do they have on the page?

17. Explain the principle of jsonp and why it is not real ajax

18. What are the local objects, built-in objects and host objects of JavaScript?

19. Convert the number 12345678 to RMB: 12345678

20. Generate 5 different random numbers

21. Remove duplicate numbers from the array

22. What is the garbage collection mechanism in JavaScript?

23. Explain the following codes

24. The output result of the following code is

25. Inheritance of JS

26. Addition and subtraction

27. What is homologous strategy?

28. Declare objects, add attributes, and output attributes

29. Match the input character: the first character must start with a letter or underscore, with a length of 5-20

30. How to add events in HTML? How many methods?

31. What are the BOM objects? List the window objects

32. The difference between bind(), live(), delegate()

33. What is a pseudo array in Javascript? How to convert a pseudo array to a standard array?

34. How to optimize your code?

35. How to achieve equal height of two columns?

36. Briefly describe the difference between readyonly and disabled

37. Explain how ajax works in as much detail as possible

38. Why is it not a good practice to extend javascript built-in objects?

39. What is the difference between browser standard mode and weird mode?

40. The following window objects of IE are correctly expressed:

1. Write a regular expression that simply describes the html tag (start tag and end tag without attributes), and remove the html tag from the string

var str = "<div>Here is div<p>The paragraph inside</p></div>";
<script type="text/javascript">
  var reg = /<\/?\w+\/?>/gi;
  var str = "<div>Here is div<p>The paragraph inside</p></div>";
  alert(str.replace(reg,""));
</script>

2. Complete the function showImg(), which requires that the display of the picture can be updated dynamically according to the options in the drop-down list

<body>
  <img id="pic"src="img1.jpg"width="200″ height="200″ />
  <br />
  <select id="sel">
    <option value="img1">city life</option>
    <option value="img2">City Morning Post</option>
    <option value="img3">beautiful country scene</option>
  </select>
</body>
<script>
  function showImg(oSel) {
    //Add code here  
    var str = oSel.value;
    document.getElementById("pic").src = str + ".jpg";
  }
</script>

3. List the common objects in the browser object model BOM and the common methods of window objects

Objects: window, document, location, screen, history, navigator
Methods: alert(), confirm(), prompt(), open(), close()  

4. List the common methods to find and access nodes of document in the Document Object Model DOM

Document.getElementById finds an element by element id
Document.getElementByName finds an element by element name
Document.getElementTagName finds an element based on the specified element name

5. What should I do if I want to get all the checkbox es in the page

<script>
  var domList = document.getElementsByTagName('input')
  var checkBoxList = [];
  var len = domList.length; //Cache to local variable
  while (len--) { //Using while is more efficient than using for loops
    if (domList[len].type == 'checkbox') {
      checkBoxList.push(domList[len]);
    }
  }
</script>

6. Briefly describe several ways to create functions

<script>
  //First (function declaration):  
  function sum1(num1, num2) {
    return num1 + num2;
  }
  //Second (function expression):
  var sum2 = function (num1, num2) {
    return num1 + num2;
  }
  //The third (function object mode):
  var sum3 = new Function("num1", "num2", "return num1+num2");
</script>

7. How does JavaScript implement inheritance?

(1) Structural inheritance law;
(2) Prototype inheritance law;
(3) Instance inheritance method.

8. Several ways of JavaScript creating objects

<script>
  //1. Create objects using json
  var obj = {};
  obj.name = 'Zhang San';
  obj.action = function () {
    alert('having dinner');
  };

  //2. Create an Object using Object
  var obj = new Object();
  obj.name = 'Zhang San';
  obj.action = function () {
    alert('having dinner');
  };

  //3. Create objects through functions.
  //(1) Use this keyword
  var obj = function () {
    this.name = 'Zhang San';
    this.age = 19;
    this.action = function () {
      alert('having dinner');
    };
  }
  //(2) Using the prototype keyword
  function obj() {}
  obj.prototype.name = 'Zhang San';
  obj.prototype.action = function () {
    alert('having dinner');
  };

  //4. Create objects through Window
  window.name = 'Zhang San';
  window.age = 19;
  window.action = function () {
    alert('having dinner');
  };

  //5. Create objects using built-in objects
  var str = new String("Instance initialization String");
  var str1 = "Directly assigned String";
  var func = new Function("x", "alert(x)"); //Sample initialization func
  var obj = new Object(); //Example initializes an Object
</script>

9. Advantages and disadvantages of iframe

advantage:
(1) Solve the loading problem of slow loading third-party content, such as icons and advertisements;
(2)Security sandbox;
(3) Load scripts in parallel.

Disadvantages:
(1) iframe will block the Onload event of the main page;
(2) Even if the content is empty, it takes time to load;
(3) No meaning.

10. Please talk about the disadvantages of cookies

(1) Limit the number and length of cookies. Each domain can only have 20 cookies at most, and the length of each cookie cannot exceed 4KB, otherwise it will be truncated.

(2) Security issues. If the cookie is intercepted, the interceptor can obtain all session information. Even encryption is not helpful, because the interceptor does not need to know the meaning of the cookie. He can achieve his goal as long as he forwards the cookie as it is.

(3) Some states cannot be saved on the client. For example, in order to prevent repeated submission of forms, we need to save a counter on the server side. If we save this counter on the client, it won't work.

11. What are the ways to delay the loading of JS?

(1) defer and async;
(2) Create DOM dynamically (create script, insert it into DOM, and call back after loading);
(3) Load js asynchronously on demand.

12. What is the difference between document.write and innerHTML?

document.write can only redraw the whole page;

innerHTML can redraw part of the page.

13. What operations will cause memory leakage?

A memory leak means that any object still exists after it no longer owns or needs it.

(1) If the first parameter of setTimeout uses a string instead of a function, memory leakage will be caused;
(2) Closure;
(3) Console log;
(4) Loop, a loop is generated when two objects refer to each other and retain each other.

14. Judge the character that appears the most times in a string and count the times

<script>
  var str = 'asdfssaaasasasasaa';
  var json = {};
  for (var i = 0; i < str.length; i++) {
    if (!json[str.charAt(i)]) {
      json[str.charAt(i)] = 1;
    } else {
      json[str.charAt(i)]++;
    }
  };
  var iMax = 0;
  var iIndex = '';
  for (var i in json) {
    if (json[i] > iMax) {
      iMax = json[i];
      iIndex = i;
    }
  }
  alert('The most frequent occurrence is:' + iIndex + 'appear' + iMax + 'second');
</script>

15. What is the event delegation?

Let's use the principle of event bubbling to replace the parent element of the triggered event.

16. What are closures, what are their characteristics, and what impact do they have on the page?

         Closure is a function that can read the internal variables of other functions. In essence, closure is a bridge connecting the internal and external functions.

17. Explain the principle of jsonp and why it is not real ajax

jsonp is to dynamically create script tags and callback functions;
Ajax is a page data operation without refresh request.

18. What are the local objects, built-in objects and host objects of JavaScript?

Local objects: array, obj, regexp, etc. can be instantiated with new;
Built in objects: gload, Math, etc. cannot be instantiated;
Host object: document, window, etc. provided by the browser.

19. Convert the number 12345678 to RMB: 12345678

<script>
  //Idea: first convert numbers into characters, str= str + '';
  //Using the inversion function, add a ',' for every three characters, and do not add the last digit; re() is a user-defined inversion function. Finally, reverse it back!
  function re(str) {
    str += '';
    return str.split("").reverse().join("");
  }
  function toRMB(num) {
    var tmp = '';
    for (var i = 1; i <= re(num).length; i++) {
      tmp += re(num)[i - 1];
      if (i % 3 == 0 && i != re(num).length) {
        tmp += ',';
      }
    }
    return re(tmp);
  }
</script>

20. Generate 5 different random numbers

<script>
  //Idea: five different numbers will be compared with all the previous numbers every time they are generated. If they are the same, the currently generated numbers will be discarded!
  var num1 = [];
  for (var i = 0; i < 5; i++) {
    num1[i] = Math.floor(Math.random() * 10) + 1; //The range is [1, 10]
    for (var j = 0; j < i; j++) {
      if (num1[i] == num1[j]) {
        i--;
        //If the i (duplicate) value is overwritten again, it can be deleted or regenerated, and the i value will replace the duplicate value
      }
    }
  }
</script>

21. Remove duplicate numbers from the array

<script>
  //Idea: each traversal is compared with all the previous ones. If they are not equal, they will be put into a new array
  Array.prototype.unique = function () {
    var len = this.length,
      newArr = [],
      flag = 1;
    for (var i = 0; i < len; i++, flag = 1) {
      for (var j = 0; j < i; j++) {
        if (this[i] == this[j]) {
          flag = 0; //After finding the same number, do not add data
        }
      }
      //The for loop will jump out of the for loop after traversing all the condition values. The loop will be terminated in advance unless there is a statement that jumps out of the loop
      flag ? newArr.push(this[i]) : '';
    }
    return newArr;
  }
</script>

22. What is the garbage collection mechanism in JavaScript?

         In Javascript, if an object is no longer referenced, the object will be recycled.

         If two objects refer to each other and are no longer referenced by the third party, the two cross referenced objects will also be recycled.

         Function a is referenced by b, and b is referenced by c outside a, so that function a will not be recycled after execution.

23. Explain the following codes

<script>
  function f1() {
    var tmp = 1;
    this.x = 3;
    console.log(tmp); //Code A
    console.log(this.x); //Code B
  }
  var obj = new f1(); //Code 1
  console.log(obj.x) //Code 2
  console.log(f1()); //Code 3
</script>

         This problem makes me understand objects and functions again. First, code 1 instantiates the class f1, which is equivalent to executing the f1 function; Therefore, at this time, A will output 1, while this in code B represents the instantiated current object obj, and B outputs 3; Code 2 will undoubtedly output 3; Code 3 is no longer A class but A function, so A outputs 1. This in code B actually represents A window object. Then this.x is A global variable, which is equivalent to an external global variable, so B outputs 3. The last generation will return underfined because f1 has no return value.

         Answer: 1, 3, 3, 1, 3, underfined.

24. The output result of the following code is

var o1 = new Object();
var o2 = o1;
o2.name = "CSSer";
console.log(o1.name);

         js has two data types: basic data type and reference data type (object Array); For variables that save basic type values, variables are accessed by value, because the actual operation is the actual saved value of the variable; For variables that store reference type values, variables are accessed by reference. We operate on the object referenced (pointed to) by the variable value.

         Answer: CSSer;

25. Inheritance of JS

<script>
  window.color = 'red';
  var o = {
    color: 'blue'
  };

  function sayColor() {
    alert(this.color);
  }
  sayColor(); //red
  sayColor.call(this); //red, this points to the window object
  sayColor.call(window); //red
  sayColor.call(o); //blue
</script>

26. Addition and subtraction

alert('5'+3);    //53 string
alert('5'+'3');  //53 string
alert('5'-3);    //2 number
alert('5'-'3');  //2 number

27. What is homologous strategy?

The security policy of the same protocol, port and domain name is the security protocol proposed by Wangjing company.

28. Declare objects, add attributes, and output attributes

<script>
  var obj = {
    name: 'leipeng',
    showName: function () {
      alert(this.name);
    }
  }
  obj.showName();
</script>

29. Match the input character: the first character must start with a letter or underscore, with a length of 5-20

<script>
  var reg = /^[a-zA-Z_][a-zA-Z0-9_]{5,20}/,
    name1 = 'leipeng',
    name2 = '0leipeng',
    name3 = 'Hello leipeng',
    name4 = 'hi';
  alert(reg.test(name1)); //true
  alert(reg.test(name2)); //false
  alert(reg.test(name3)); //false
  alert(reg.test(name4)); //false
</script>

30. How to add events in HTML? How many methods?

(1) Add directly to the label, ο nclick="fun()";

(2) JS add, obj.onclick = method;

(3) Modern events

        IE: obj.attachEvent('onclick', method);
        FF: obj.addEventListener('click', method, false);

31. What are the BOM objects? List the window objects

(1) Window object is the top-level object of JS, and other BOM objects are the attributes of window object;
(2) Document object, document object;
(3) location object, browser current URL information;
(4) navigator object, browser information;
(5) Screen object, client screen information;
(6) History object, the browser accesses history information;

32. The difference between bind(), live(), delegate()

         Bind: bind event. It has no effect on the newly added event. The method is used to attach a handler to the event of each matching element and return the jQuery object.

        live: attaches an event handler to the specified event of all elements that match the current selector, including existing or future additions, and returns a jQuery object.

         delegate: the method attaches the handler to one or more events that match all elements (existing or future) of the selector based on a specific set of root elements.  

33. What is a pseudo array in Javascript? How to convert a pseudo array to a standard array?

         Pseudo array (class array): you cannot directly call array methods or expect the length attribute to have any special behavior, but you can still traverse them like a real array. Typically, the argument parameter of the function, as well as calls such as getElementsByTagName and document.childNodes, all return NodeList objects and belong to pseudo arrays.

         You can use Array.prototype.slice.call(fakeArray) to convert an Array into a real Array object.

34. How to optimize your code?

(1) Code reuse;

(2) Avoid global variables (namespace, enclosed space, modular mvc..);

(3) Split functions to avoid overstaffing;

(4) Notes.

35. How to achieve equal height of two columns?

<div id="container" style="display: table;width: 100%;">
    <div id="left" style="background-color: red;display: table-cell;">
      content<br />
      content<br />
      content<br />
      content<br />
      content<br />
      content<br />
    </div>
    <div style="display:table-cell;"></div>
    <div id="right" style="background-color: blue;display: table-cell">
      content
    </div>
  </div>

36. Briefly describe the difference between readyonly and disabled

         ReadOnly and Disabled are used to prevent users from changing the contents of form fields; However, there are some differences between the two:

         Readonly is valid only for input(text/password) and textarea, while disabled is valid for all form elements, including select,radio,checkbox,button, etc.

         After the form element is disabled, if we submit the form in the form of POST or GET, the value of this element will not be passed, but readonly will pass the value.

37. Explain how ajax works in as much detail as possible

         The working principle of Ajax is equivalent to adding an intermediate layer between the user and the server, which makes the user operation asynchronous with the server response. In this way, the work of some previous servers is transferred to the client, which is conducive to the idle processing capacity of the client, and reduces the burden of servers and bandwidth, so as to save ISP space and bandwidth rental cost.

         Simply put, send asynchronous requests to the server through the XMLHttpRequest object, obtain data from the server, and then use javascript to operate the DOM to update the page. The most critical step is to obtain the request data from the server. To understand this process and principle, we must understand XMLHttpRequest.

38. Why is it not a good practice to extend javascript built-in objects?

         Because I don't know when the browser or javascript itself will implement this method, and it is likely to be inconsistent with your extended implementation. By then, your javascript code may have been executed in countless pages for several years, and the implementation of the browser will cause all the code using the extension prototype to crash.

39. What is the difference between browser standard mode and weird mode?

         The so-called standard mode means that the browser parses and executes code according to W3C standard; Weird mode is to use the browser's own way to parse and execute code. Because different browsers parse and execute in different ways, we call it weird mode.

40. The following window objects of IE are correctly expressed:

A. The window.opener attribute itself points to the window object √
B. The window. Reload () method can be used to refresh the current page   It should be location.reload or window.location.reload
C. Both window. Location = "a.html" and window.location.href = "a.html" are used to replace the current page with a.html page √
D. The global variable g is defined; The variable √ can be accessed in window.g

Keywords: Javascript Interview regex

Added by TFD3 on Wed, 17 Nov 2021 13:59:49 +0200