Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the advanced problems of JavaScript?

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly talks about "what are the advanced problems of JavaScript". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the advanced problems of JavaScript"?

1. What is the output?

Function sayHi () {console.log (name) console.log (age) var name = 'Lydia' let age = 21} sayHi ()

A: Lydia and undefined

B: Lydia and ReferenceError

C: ReferenceError and 21

D: undefined and ReferenceError

Answer: d

Inside the function, we first declare the name variable through the var keyword. This means that the variable is promoted (the memory space is set during the creation phase), and the default value is undefined until the program runs to the location where the variable is defined. Because we have not yet reached the position where the variable is defined when we print the name variable, the value of the variable is maintained as undefined.

Variables declared by the let and const keywords are also promoted, but unlike var, they are not initialized. They cannot be accessed until we declare (initialize) them. This behavior is called a temporary dead zone. When we try to access them before the declaration, JavaScript will throw a ReferenceError error.

two。 What is the output?

For (var I = 0; I

< 3; i++) { setTimeout(() =>

Console.log (I), 1)} for (let I = 0; I

< 3; i++) { setTimeout(() =>

Console.log (I), 1)}

A: 0 1 2 and 0 1 2

B: 0 1 2 and 3 3 3

C: 3 3 3 and 0 1 2

Answer: C

Because of JavaScript's event loop, the setTimeout callback is not executed until the traversal is over. Because traversal I in the first traversal is declared by the var keyword, this value is in global scope. During the traversal, we increment the value of I each time through the unary operator + +. When the setTimeout callback is executed, the value of I is equal to 3.

In the second traversal, traversal I is declared by the let keyword: variables declared by the let and const keywords have block-level scope (referring to anything in {}). During each traversal, I has a new value, and each value is in scope within the loop.

3. What is the output?

Const shape = {radius: 10, diameter () {return this.radius * 2}, perimeter: () = > 2 * Math.PI * this.radius} shape.diameter () shape.perimeter ()

A: 20 and 62.83185307179586

B: 20 and NaN

C: 20 and 63

D: NaN and 63

Answer: B

Note that the value of diameter is a regular function, but the value of perimeter is an arrow function.

For arrow functions, the this keyword points to its current scope (simply a regular function that contains arrowhead functions, or a global object if there is no regular function), which is different from regular functions. This means that when we call perimeter, this points not to the shape object, but to its surrounding scope (in this case, window).

There is no radius property in window, so undefined is returned.

4. What is the output?

+ true;! "Lydia"

A: 1 and false

B: false and NaN

C: false and false

Answer: a

The unary operator plus sign attempts to convert bool to number. If true is converted to number, it is 1, and false is 0.

The string 'Lydia' is a true value, which returns false if the true value is reversed.

5. Which one is invalid?

Const bird = {size: 'small'} const mouse = {name:' Mickey', small: true}

A: mouse.bird.size

B: mouse [bird.size]

Mouse [bird ["size"]

D: all valid

Answer: a

In JavaScript, the keys of all objects is a string (unless the object is Symbol). Although we may not define them as strings, they are always converted to strings at the bottom.

When we use parenthesis syntax ([]), JavaScript interprets (or unboxes) statements. It first sees the first opening parenthesis [and moves on until the closing parenthesis is found]. Only in this way will it calculate the value of the statement.

Mouse [bird.size]: first calculate the bird.size, which results in small. Mouse ["small"] returns true.

None of this would have happened if you had used a little grammar. Mouse does not have the key of bird, which means that mouse.bird is undefined. Then when we use the point syntax mouse.bird.size, because mouse.bird is undefined, this becomes undefined.size. This behavior is invalid and an error similar to Cannot read property "size" of undefined is thrown.

6. What is the output?

Let c = {greeting: 'heyweights'} let d d = c c.greeting = 'Hello' console.log (d.greeting)

A: Hello

B: undefined

C: ReferenceError

D: TypeError

Answer: a

In JavaScript, when you set two objects to be equal to each other, they interact by reference.

First, the value of the variable c is an object. Next, we assign d the same reference as the c object.

So when we change one of the objects, we actually change all the objects.

7. What is the output?

Let a = 3 let b = new Number (3) let c = 3 console.log (a = b) console.log (a = = b) console.log (b = = c)

A: true false true

B: false false true

C: true false false

D: false true true

Answer: C

New Number () is a built-in function constructor. Although it looks like a number, it's not really a real number: it has a bunch of extra features and it's an object.

When we use the = = operator, it only checks to see if they have the same value. Because their values are all 3, they return true.

Then, when we use the = = operator, both values and types should be the same. New Number () is an object rather than a number, so it returns false.

8. What is the output?

Class Chameleon {static colorChange (newColor) {this.newColor = newColor return this.newColor} constructor ({newColor = 'green'} = {}) {this.newColor = newColor}} const freddie = new Chameleon ({newColor:' purple'}) freddie.colorChange ('orange')

A: orange

B: purple

C: green

D: TypeError

Answer: d

ColorChange is a static method. Static methods are designed to be used only by the constructor that created them (that is, Chameleon) and cannot be passed to the instance. Because freddie is an instance, static methods cannot be used by the instance, so a TypeError error is thrown.

9. What is the output?

Let greeting greetign = {} / / Typo! Console.log (greetign)

A: {}

B: ReferenceError: greetign is not defined

C: undefined

Answer: a

The code prints out an object because we created an empty object on the global object! When we miswrite greeting as greetign, the JS interpreter actually treats it as global.greetign = {} (or window.greetign = {}) in the browser.

To avoid this problem, we can use "use strict". This ensures that you must assign a value when you declare a variable.

10. What happens when we do this?

Function bark () {console.log ('wood')} bark.animal = 'dog'

A: normal operation!

B: SyntaxError. You can't add properties to a function in this way.

C: undefined

D: ReferenceError

Answer: a

This is possible in JavaScript, because functions are objects! (all but the basic types are objects)

A function is a special object. The code you wrote is not really an actual function. A function is an object that has properties, and properties can also be called.

11. What is the output?

Function Person (firstName, lastName) {this.firstName = firstName; this.lastName = lastName;} const member = new Person ("Lydia", "Hallie"); Person.getFullName = function () {return `${this.firstName} ${this.lastName}`;} console.log (member.getFullName ())

A: TypeError

B: SyntaxError

C: Lydia Hallie

D: undefined undefined

Answer: a

You can't add properties to a constructor like a regular object. If you want to add features to all instances at once, you should use prototypes. So in this example, use the following ways:

Person.prototype.getFullName = function () {return `${this.firstName} ${this.lastName}`;}

That's what makes member.getFullName () work. Why is it beneficial to do so? Suppose we add this method to the constructor itself. Maybe not every Person instance needs this method. This wastes a lot of memory space because they still have this property, which takes up the memory space of each instance. Conversely, if we only add it to the prototype, it only exists in one location in memory, but all instances can access it!

twelve。 What is the output?

Function Person (firstName, lastName) {this.firstName = firstName this.lastName = lastName} const lydia = new Person ('Lydia',' Hallie') const sarah = Person ('Sarah',' Smith') console.log (lydia) console.log (sarah)

A: Person {firstName: "Lydia", lastName: "Hallie"} and undefined

B: Person {firstName: "Lydia", lastName: "Hallie"} and Person {firstName: "Sarah", lastName: "Smith"}

C: Person {firstName: "Lydia", lastName: "Hallie"} and {}

D:Person {firstName: "Lydia", lastName: "Hallie"} and ReferenceError

Answer: a

For sarah, we did not use the new keyword. When using new, this refers to the empty object we created. When new is not used, this refers to a global object (global object).

We say this.firstName equals "Sarah" and this.lastName equals "Smith". What we're actually doing is defining global.firstName = 'Sarah' and global.lastName =' Smith'. And sarah itself is undefined.

13. What are the three stages of event propagation?

A: Target > Capturing > Bubbling

B: Bubbling > Target > Capturing

C: Target > Bubbling > Capturing

D: Capturing > Target > Bubbling

Answer: d

During the capturing phase, events propagate down from the ancestor element to the target element. Bubbling begins when the event reaches the target element.

14. All objects have prototypes.

A: true

B: false

Answer: B

All objects have prototypes except basic objects (base object). Basic objects can access some methods and properties, such as .toString. This is why you can use the built-in JavaScript method! All of these methods are available on the prototype. Although JavaScript cannot find these methods directly on the object, JavaScript will find them along the prototype chain so that you can use them.

15. What is the output?

Function sum (a, b) {return a + b} sum (1,'2')

A: NaN

B: TypeError

C: "12"

D: 3

Answer: C

JavaScript is a dynamically typed language: we do not specify the types of certain variables. Values can be automatically converted to another type without your knowledge, which is called implicit type conversion (implicit type coercion). Coercion refers to converting one type to another.

In this case, JavaScript converts the number 1 to a string so that the function makes sense and returns a value. When the number type (1) and the string type ('2') are added, the number is treated as a string. We can concatenate strings such as "Hello" + "World". What happens here is "1" + "2", which returns "12".

16. What is the output?

Let number = 0 console.log (number++) console.log (+ + number) console.log (number)

A: 1 1 2

B: 1 2 2

C: 0 2 2

D: 0 1 2

Answer: C

The operator + + after unary increment:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Return value (return 0)

Value increments (number is now 1)

The self-increasing operator + + before unary:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Value increments (number is now 2)

Return value (return 2)

The result is 0.22.

17. What is the output?

Function getPersonInfo (one, two, three) {console.log (one) console.log (two) console.log (three)} const person = 'Lydia' const age = 21 getPersonInfo` ${person} is ${age} years old`

A: "Lydia" 21 ["," is "," years old "]

B: ["," is "," years old "]" Lydia "21

C: "Lydia" ["," is "," years old "] 21

Answer: B

If you use the tag template literal, the value of the first parameter always contains an array of strings. The rest of the parameters get the value of the passed expression!

18. What is the output?

Function checkAge (data) {if (data = = {age: 18}) {console.log ('You are an adultudes')} else if (data = = {age: 18}) {console.log ('You are still an adult.')} else {console.log (`Hmm..) You don't have an age I guess`)}} checkAge ({age: 18})

A: You are an adult!

B: You are still an adult.

C: Hmm.. You don't have an age I guess

Answer: C

When testing equality, primitive types are compared by their values (value), while objects are compared by their reference. JavaScript checks whether the object has a reference to the same location in memory.

The two objects we are comparing in the title are not the same reference: the memory location of the object reference passed as a parameter is different from the memory location referenced by the equal object.

That's why {age: 18} = = {age: 18} and {age: 18} = = {age: 18} both return false.

19. What is the output?

Function getAge (... args) {console.log (typeof args)} getAge (21)

A: "number"

B: "array"

C: "object"

D: "NaN"

Answer: C

The extension operator (... args) returns an array of arguments. The array is an object, so typeof args returns "object".

20. What is the output?

Function getAge () {'use strict' age = 21 console.log (age)} getAge ()

A: 21

B: undefined

C: ReferenceError

D: TypeError

Answer: C

With "use strict", you can make sure that global variables are not accidentally declared. We never declare the variable age because we use "use strict", which throws a reference error. If we don't use "use strict", it will work because the property age will be added to the global object.

21. What is the output?

Const sum = eval ('10105')

A: 105

B: "105"

C: TypeError

D: "10-10-5"

Answer: a

The code is passed in as a string, which is evaluated by eval. If it is an expression, as in this case, it evaluates the expression. The expression is 10 * 10 + 5. This returns the number 105.

twenty-two。 How long can cool_secret be accessed?

SessionStorage.setItem ('cool_secret', 123)

A: never, data will never be lost.

B: when the user closes the tab.

C: when the user closes the entire browser, not just the tab.

D: when the user shuts down the computer.

Answer: B

The data stored by sessionStorage is not deleted until the tab tab is closed.

If you use localStorage, the data will always be there unless localStorage.clear () is called.

23. What is the output?

Var num = 8 var num = 10 console.log (num)

A: 8

B: 10

C: SyntaxError

D: ReferenceError

Answer: B

Using the var keyword, you can declare multiple variables with the same name. The variable then holds the latest value.

You can't use let or const to do this because they are block scoped.

24. What is the output?

Const obj = {1:'a', 2: 'baked, 3:' c'} const set = new Set ([1,2,3,4,5]) obj.hasOwnProperty ('1') obj.hasOwnProperty (1) set.has ('1') set.has (1)

A: false true false true

B: false true true true

C: true true false true

D: true true true true

Answer: C

The keys of all objects (excluding Symbol) are strings at the bottom, even if you don't enter them as strings yourself. This is why obj.hasOwnProperty ('1') also returns true.

For collections, this is not how it works. There is no '1':set.has (' 1') in our collection that returns false. It has a numeric type of 1meme set.has (1) that returns true.

25. What is the output?

Const obj = {a: 'one', b:' two', a: 'three'} console.log (obj)

A: {a: "one", b: "two"}

B: {b: "two", a: "three"}

C: {a: "three", b: "two"}

D: SyntaxError

Answer: C

If you have two keys with the same name, the key will be replaced. It is still where the first key appears, but the value is the value of the last key.

twenty-six。 The JavaScript global execution context does two things for you: global objects and the this keyword.

A: true

B: false

C: it depends

Answer: a

The basic execution context is the global execution context: it is accessible everywhere in the code.

twenty-seven。 What is the output?

For (let I = 1; I

< 5; i++) { if (i === 3) continue console.log(i) } A: 1 2 B: 1 2 3 C: 1 2 4 D: 1 3 4 答案: C 如果某个条件返回 true,则 continue 语句跳过本次迭代。 28. 输出是什么? String.prototype.giveLydiaPizza = () =>

{return 'Just giveLydia pizza alreadyreaders'} const name = 'Lydia' name.giveLydiaPizza ()

A: Just give Lydia pizza already!

B: TypeError: not a function

C: SyntaxError

D: undefined

Answer: a

String is a built-in constructor to which we can add attributes. I just added a method to its prototype. The primitive type string is automatically converted to a string object and generated by the string prototype function. Therefore, all string (string objects) can access this method!

twenty-nine。 What is the output?

Const a = {} const b = {key:'b'} const c = {key:'c'} a [b] = 123a [c] = 456 console.log (a [b])

A: 123

B: 456

C: undefined

D: ReferenceError

Answer: B

Object is automatically converted to a string. We tried to set an object b to the key of object a, with a corresponding value of 123.

However, when an object is serialized, it becomes "[object Object]". So what we're saying here is that a ["[object Object]"] equals 123. Then, we do the same thing again, c is another object, and there is also implicit serialization, so a ["[object Object]"] = 456.

Then we print a [b], that is, a ["[object Object]"]. It was just set to 456, so 456 is returned.

thirty。 What is the output?

Const foo = () = > console.log ('First') const bar = () = > setTimeout (() = > console.log (' Second')) const baz = () = > console.log ('Third') bar () foo () baz ()

A: First Second Third

B: First Third Second

C: Second First Third

D: Second Third First

Answer: B

We have a setTimeout function and call it first. However, it is the last to print the log.

This is because in browsers, we have not only a runtime engine, but also something called WebAPI. WebAPI provides setTimeout functions, as well as others, such as DOM.

After pushing callback to WebAPI, the setTimeout function itself (but not a callback!) Will pop up from the stack.

Now, foo is called to print "First".

Foo pops up from the stack and baz is called. Print "Third".

WebAPI cannot add content to the stack at any time. Instead, it pushes the callback function to a place called queue.

This is where the event loop begins to work. An event loop looks at the stack and task queue. If the stack is empty, it accepts the first element on the queue and pushes it onto the stack.

Bar is called, prints "Second", and then it pops up on the stack.

thirty-one。 What is event.target when a button is clicked?

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report