JS basic theoretical knowledge

1. Tell me about your understanding of the box model??

When a document is laid out, the browser's rendering engine will represent all elements as rectangular boxes according to one of the standard CSS basic box model s

A box consists of four parts: content, padding, border and margin

In CSS, the box model can be divided into:

  • W3C standard box model
  • IE weird box model

2. Why are there gaps between two adjacent inline block nodes and how to solve them?

When the element is treated as an in-line element for typesetting, the carriage return and line feed in the original HTML code are converted into a blank character. When the font is not 0, the blank character occupies a certain width, so there is a gap between the elements of the inline block. The spacing between these elements will vary with the font size. When the in-line element font size: 16px, the spacing is 8px.

Solution 1: set font size: 0 for parent element; Set the corresponding font size for the child element

Solution 2: change the writing method. The reason for the white space between elements is the space between tag segments. Therefore, remove the space in HTML and the natural space will disappear

3. Why do floats occur and when do I need to clear them? How to clear floating?

If there is a child box in a parent box, and the parent box is not set high, and the child box floats in the parent box, the height of the parent box in the future will be 0 Since the height of the parent box is 0, the following elements will be filled automatically. The width of the child box is set, and the parent box cannot be opened, so the floating is cleared at this time.

The method is as follows

  1. Add overflow: hidden to the parent element;
  2. Add a new label under the parent element and set clear:both for the new label;
  3. Use pseudo element: after to add the following attributes to the parent element: after {content: ''; / set the content to null / display:block; / convert text to block level element / clear:both; / clear floating /} parent element {zoom:1;}
  4. Use double pseudo elements to clear floating parent elements: before, parent elements: after {content: ""; display: block; clear: both;} Parent element {zoom: 1;}

Recommended method 3, quite rigorous

4. What is the difference between href and src?

When developing a page, we sometimes need to refer to some external resources, and we often can't distinguish href from src. Let's talk about the difference between them, so that we can know when we use them.

1.href: Hypertext Reference is the abbreviation of Hypertext Reference. It points to some network resources and establishes the link relationship with the current element or this document. When it is loaded, the processing of the current document will not stop, and the browser will continue to go down. Commonly used in a, link and other tags.

<a href="http://www.baidu.com"></a>
<link type="text/css" rel="stylesheet" href="common.css">

As shown above, when the browser loads the link tag, it will recognize that it is a CSS document and download the CSS document in parallel, but it will not stop loading the subsequent content of the current page. This is why @ import is not recommended to load CSS.

2.src: the abbreviation of source, which refers to a reference to a resource. The content it points to will be embedded in the location of the current tag. Because the content of src is an essential part of the page, the browser will stop processing the subsequent documents when parsing src until the content of src is loaded. It is commonly used in script, img and iframe tags. We recommend that js files be placed at the end of HTML documents. If the js file is placed in the head tag, you can use window Onload implements the final loading of js.

<img src="img/girl.jpg">
<frame src="top.html">
<iframe src="top.html">
<script src="show.js">

Summary: href is used to establish the relationship (link) between the current page and the referenced resources, while src replaces the current tag. When href is encountered, the page will load subsequent content in parallel; Unlike src, the browser needs to load the contents of src before moving on.

5. Six inheritance methods in javascript

The inherited operation needs to have a parent class. Here, a constructor plus a prototype is used to create one:

// super
function Person(name){
	this.name = name;
}
Person.prototype.job = 'frontend';
Person.prototype.sayHello = function() {
	console.log('Hello '+this.name);
}
var person = new Person('jia ming');
person.sayHello(); // Hello jia ming

Prototype chain inheritance

// Prototype chain inheritance
function Child() {
	this.name = 'child';
}
Child.prototype = new Person();
var child = new Child();
console.log(child.job); // frontend
// instanceof determines whether an element is on the prototype chain of another element
// child is an instance of the Person class
console.log(child instanceof Person); // true

Key point: the subclass prototype is equal to the instance child of the parent class prototype = new Person()

The detailed explanation of the prototype chain was mentioned in an article before Deep understanding of prototype objects and prototype chains

characteristic:

  1. The inheritable properties of an instance are: the properties of the instance constructor, the properties of the parent class constructor, and the properties on the parent class prototype. (the new instance does not inherit the properties of the parent instance)

matters needing attention:

  1. The new instance cannot pass arguments to the parent constructor
  2. Inheritance single
  3. All new instances share the properties of the parent instance. (the properties on the prototype are shared. If one instance modifies the prototype properties, the prototype properties of another instance will also be modified.)

Borrow constructor

// Borrowing constructor inheritance
function Child() {
	Person.call(this, 'reng');
}
var child = new Child();
console.log(child.name); // reng
console.log(child instanceof Person); // false
child.sayHello(); // An error is reported. You cannot inherit anything from the parent prototype

Key point: use call or apply to introduce the parent constructor into the subclass function (the self-execution (copy) of the parent function is made in the subclass function) person call(this, 'reng')

There was a previous article on the use of call, apply and bind Talk about call, apply and bind in JavaScript mention.

characteristic:

  1. Only the properties of the parent class constructor are inherited, and the properties of the parent class prototype are not inherited
  2. The precautions (disadvantages) 1, 2 and 3 of prototype chain inheritance are solved
  3. You can inherit the properties of multiple constructors (call can be multiple)
  4. Parameters can be passed to the parent instance in the child instance

matters needing attention:

  1. Only properties of the parent constructor can be inherited
  2. Cannot implement reuse of constructors. (to be called again every time)
  3. Each new instance has a copy of the constructor, which is bloated

Combinatorial inheritance

Composite inheritance is a combination of prototype chain inheritance and borrowing constructor inheritance.

// Combinatorial inheritance
function Child(name) {
	Person.call(this, name);
}
Child.prototype = new Person();
var child = new Child('jia');
child.sayHello(); // Hello jia
console.log(child instanceof Person); // true

Key point: it combines the advantages of two modes - call to parent class and prototype

characteristic:

  1. It can inherit the properties on the parent class prototype, pass parameters and reuse
  2. The constructor property introduced by each new instance is private

matters needing attention:

  1. Called the constructor of the parent class twice (memory consumption)
  2. The constructor of the subclass will replace the constructor of the parent class on the prototype (call is equivalent to getting a copy of the constructor of the parent class)

Prototype inheritance

// First, a function container is encapsulated to hold the inherited prototype and output object
function object(obj) {
	function F() {}
	F.prototype = obj;
	return new F();
}
var super0 = new Person();
var super1 = object(super0);
console.log(super1 instanceof Person); // true
console.log(super1.job); // frontend

Key point: wrap an object with a function, and then return the call of the function. The function becomes an instance or object that can add properties at will. Object.create() is the principle.

characteristic:

  1. Similar to copying an object, wrap it with a function

matters needing attention:

  1. All instances inherit the properties on the prototype
  2. Reuse cannot be achieved. (new instance properties are added later)

**Object. The create () method regulates prototype inheritance** This method takes two parameters, an object used as a prototype for the new object and (optionally) an object that defines additional properties for the new object.

// When passing a parameter
var anotherPerson = Object.create(new Person());
console.log(anotherPerson.job); // frontend
console.log(anotherPerson instanceof Person); // true
// When passing two parameters
var anotherPerson = Object.create(new Person(), {
	name: {
		value: 'come on'
	}
});
anotherPerson.sayHello(); // Hello come on

Parasitic inheritance

function object(obj) {
	function F(){}
	F.prototype = obj;
	return new F();
}
var sup = new Person();
// The above is prototype inheritance. Put another shell for prototype inheritance to pass parameters
function subobject(obj) {
	var sub = object(obj);
	sub.name = 'ming';
	return sub;
}
var sup2 = subobject(sup);
// After this function is declared, it becomes an object that can add attributes
console.log(sup2.name); // 'ming'
console.log(sup2 instanceof Person); // true

Key point: it is to put a shell on the prototype inheritance.

characteristic:

  1. The user-defined type is not created, because it only sets a shell and returns an object. Naturally, this function becomes a new object created.

matters needing attention:

  1. No prototype is used and cannot be reused

Parasitic combinatorial inheritance

Like composite inheritance, it is commonly used.

Parasitism: returns an object within a function and calls it.

Combination:

  1. The prototype of the function is equal to another instance
  2. Use apply or call to introduce another constructor in the function, which can pass parameters
// parasitic
function object(obj) {
	function F(){}
	F.prototype = obj;
	return new F();
}
// object is another representation of an F instance
var obj = object(Person.prototype);
// The prototype of obj instance (F instance) inherits the prototype of parent function
// The above is more like prototype chain inheritance, but only inherits the prototype properties

// combination
function Sub() {
	this.age = 100;
	Person.call(this); // This inherits the properties of the parent constructor
} // It solves the characteristics of combined twice calling constructor attribute

// a key
Sub.prototype = obj;
console.log(Sub.prototype.constructor); // Person
obj.constructor = Sub; // Be sure to repair the instance
console.log(Sub.prototype.constructor); // Sub
var sub1 = new Sub();
// The Sub instance inherits the constructor attribute, the parent class instance, and the function attribute of the object
console.log(sub1.job); // frontend
console.log(sub1 instanceof Person); // true

Key: fixed the problem of composite inheritance

In the above question, you may find such a comment obj constructor = Sub; // Be sure to repair the instance. Why fix the pointing of subclass constructor?

Because when the pointer is not corrected and the constructor returns, it may cause confusion in calling the value of the property or method with the same name. For example:

function Car() { }
Car.prototype.orderOneLikeThis = function() {  // Clone producing function
    return new this.constructor();
}
Car.prototype.advertise = function () {
    console.log("I am a generic car.");
}

function BMW() { }
BMW.prototype = Object.create(Car.prototype);
BMW.prototype.constructor = BMW;              // Resetting the constructor property
BMW.prototype.advertise = function () {
    console.log("I am BMW with lots of uber features.");
}

var x5 = new BMW();

var myNewToy = x5.orderOneLikeThis();

myNewToy.advertise(); // => "I am BMW ..." if `BMW.prototype.constructor = BMW;` is not 
                      // commented; "I am a generic car." otherwise.

6. What are the basic types of js

Undefined, Null, Boolean, Number, String

7. Please describe the difference between cookies, sessionStorage and localStorage?

cookie:

O cookies are data (usually encrypted) stored on the user's Client Side by the website to identify the user.

o cookie data is always carried in the http request of the same origin (even if it is not needed), and it will be passed back and forth between the browser and the server.

sessionStorage * * * * and localStorage will not automatically send data to the server, but only save it locally.

Storage size:

o cookie data size cannot exceed 4k.

O although sessionstorage and localStorage also have storage size restrictions, they are much larger than cookie s, which can reach 5M or more.

Duration:

o localStorage stores persistent data. After the browser is closed, the data will not be lost unless the data is actively deleted;

o sessionStorage data is automatically deleted after the current browser window is closed.

O cookies are valid until the set cookie expiration time, even if the window or browser is closed

Different scopes:

o sessionStorage is not shared in different browser windows, even the same page;

o localStorage is shared in all source windows; Cookies are also shared in all cognate windows.

8. What is the output of the following code? Explain why.

var a; 
alert(typeof a); 
alert(b); 
b=10;
alert(typeof b);

var a;

alert(typeof a); // "undefined"

//alert(b); // report errors

b=10;

alert(typeof b);//"number"

Explanation: undefined is a data type with only one value. This value is "undefined". var is used

When a variable is declared but its assignment is not initialized, the value of the variable is undefined. And b because it is not stated that

report errors. Note that undeclared variables are different from declared unassigned variables.

undefined will be generated in the following three cases:

1. A variable is defined but not assigned

2. To get a property or method that does not exist on an object:

3. An element in an array that has no assigned value

Note that the distinction between undefined and not defined is different

9. Output today's date in the form of YYYY-MM-DD,

For example, if today is April 8, 2021, output 2021-04-08

<script>
    var d = new Date(); // Get the year, and getFullYear() returns a 4-digit number 
    var year = d.getFullYear();
    // Get the month. The month is special. 0 is January and 11 is December 
    var month = d.getMonth() + 1;
    // Become two 
    month = month < 10 ? '0' + month : month;
    // Acquisition day 
    var day = d.getDate(); day = day < 10 ? '0' + day : day;
    alert(year + '-' + month + '-' + day);
</script>

10. Look at the following code, what will be output? Why?

<script>
    var foo = 1;
    function f(){
        console.log(foo);
        var foo = 2;
        console.log(foo);
    }

    f();
</script>

Answer: output undefined and 2. The above code is equivalent to:

var foo = 1;

function(){

var foo;

console.log(foo);

//undefined

foo = 2;

console.log(foo);

// 2;

}

Function declarations and variable declarations are implicitly promoted to the top of the current scope by the JavaScript engine, but only the name is promoted

The assignment part will not be promoted

11. What are the common methods of Javscript array (write at least eight)

  • push()
  • unshift()
  • splice()
  • concat()
  • pop()
  • shift()
  • splice()
  • slice()
  • indexOf()
  • includes()
  • find()
  • reverse()
  • sort()
  • join()
  • some()
  • every()
  • forEach()
  • filter()
  • map()

12. When submitting git, you will be prompted how to set the mailbox

The setting method is to right-click the directory where the project is located, select git bash command tool, and enter:

git config user.name your target user name;

git config user.email your target email name;

13. The similarities and differences of apply, call and bind?

  • The same point: the direction of this can be changed. The first parameter is the object to which this points, and subsequent parameters can be used to transfer parameters.
  • Differences: apply and call are direct calls to functions, and bind returns a function. They are not called directly and need to be called again.

14. DOM operations -- how to add, remove, move, copy, create, and find nodes.

answer:

  1. Create a new node

createDocumentFragment() / / create a DOM fragment

createElement() / / create a specific element

createTextNode() / / create a text node

  1. Add, remove, replace, insert

appendChild()

removeChild()

replaceChild()

insertBefore() / / insert a new child node before the existing child node

  1. lookup

getElementsByTagName()

//By label name

getElementsByName() //

Through the value of the Name attribute of the element (IE), it has strong fault tolerance and will get an array,

This includes the with id equal to the value of name)

getElementById() / / uniqueness through element Id

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

For example: var str = 'asdfssaaaa';

Print result: the most frequent occurrences are: a appears 9 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>

16. What is a closure? Write a simple closure

Closures are functions that can read internal variables of other functions. (function set function, internal function uses variables of external function)

<script>
    function outer() {
        var num = 1;
        function inner() {
            var n = 2;
            alert(n + num);
        }
        return inner;
    }
    outer()();
</script>

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

Answer:

1. Window object is the top-level object of JS, and other BOM objects are window objects

Attributes;

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;

18. What is the difference between GET and POST in HTTP protocol? What scenarios are applicable

Answer:

GETPOST
cacheCan be cachedCannot cache
historyParameters remain in browser historyParameters are not saved in browser history
Limit on data lengthWhen sending data, the GET method adds data to the URL; The length of the URL is limited (the maximum length of the URL IE is 2048 characters, and the maximum length of chrome is 8182 characters)unlimited
Restrictions on data typesOnly ASCII characters are allowedNo restrictions, binary data is also allowed
SecurityCompared with POST, GET is less secure because the data sent is part of the URLPOST is safer than GET because parameters are not saved in browser history or web server logs
visibility The data is visible to everyone in the URLData is not displayed in the URL

Applicable scenarios:

post is generally used for form submission

get is generally used for simple data query, which is not so strict

19. Using regular expressions, write a string of 6 ~ 30 that starts with a letter and consists of numbers, letters and underscores

Answer: var reg=/ 1[\da-zA-Z_]{5,29}/;

20. What is the principle of ajax? How

Full name of AJAX (Async Javascript and XML)

Asynchronous JavaScript and XML is a web development technology for creating interactive web applications. It can exchange data with the server and update some web pages without reloading the whole web page

The principle of Ajax is simply to send an asynchronous request 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 implementation of Ajax asynchronous interaction requires the cooperation of server logic. The following steps need to be completed:

  • Create the XMLHttpRequest object, the core object of Ajax
  • Establish a connection with the server through the open() method of the XMLHttpRequest object
  • Build the data content required by the request and send it to the server through the send() method of the XMLHttpRequest object
  • Listen for your communication status on the server side through the onreadystatechange event provided by the XMLHttpRequest object
  • Accept and process the data results responded by the server to the client
  • Update the processing results to the HTML page

1. Create a json file named newsdata json, which is the news in the following list, uses ajax request to obtain the data in the json file and render it (20 points)

  • The Fuxing railway entered Lhasa Nyingchi, Tibet, and was put into operation on the 25th

  • On behalf of countries with similar views, China criticized the military intervention of relevant countries at the United Nations Human Rights Council for harming human rights

  • The Centennial struggle history of our party is the history of seeking happiness for the people

  • A new round of rainfall in Jiangnan and other places started over the weekend, and high temperatures continued in Henan, Hebei and other places

  • The whole Qinghai Tibet railway has been open to traffic for 15 years: crossing the heavenly road of "life forbidden zone"

  • Geng Shuang: China firmly supports Argentina's legitimate claim for sovereignty over the Malvinas Islands

  1. a-ZA-Z ↩︎

Keywords: Javascript html css

Added by ohjay on Tue, 25 Jan 2022 01:28:17 +0200