30 JavaScript questions and answers that you "can't do all"

Source: Internet
Author: User
Tags closure

1, the following expression runs as a result:

    1. ["1", "2", "3"].map (parseint)

a.["1", "2", "3"]
b.[1,2,3]
c.[0,1,2]
D. Other

2, the following expression runs as a result:

    1. [typeof null, NULL instanceof Object]

A.["Object", false]
B.[null,false]
C.["Object", True]
D. Other

3, the following expression runs as a result:

    1. [[3,2,1].reduce (Math.pow), [].reduce (MATH.POW)]

A. Error
b.[9,0]
C.[9,nan]
D.[9,undefined]

4, the following expression runs as a result:

    1. var val = ' value ';
    2. Console.info (' Value ID ' + (val = = = ' value ')? ' Something ': ' Nothing ');

A.something
B.nothing
C.nan
D. Other

5, the following expression runs as a result:

    1. var name = ' World ';
    2. (function () {
    3. if (typeof name = = = ' undefined ') {
    4. var name = "Jack";
    5. Console.info (' Goodbye ' + name);
    6. }else{
    7. Console.info (' Hello ' + name);
    8. }
    9. })();

A.goodbye Jack.
B.hello Jack.
C.goodbye undefined
D.hello undefined

6, the following expression runs as a result:
var START = END-100;
var count = 0;
for (var i = START; I <= END; i++) {
Count + +;
}
Console.info (count);
a.0
b.100
C.101
D. Other

7, the following expression runs as a result:
var arr = [0,1,2];
ARR[10] = 10;
Arr.filter (function (x) {return x = = = undefined});
a.[undefined x 7]
B.[0,1,2,10]
C.[]
D.[undefined]

8, the following expression runs as a result:
var = 0.2;
var one = 0.1;
var eight = 0.8;
var six = 0.6;
[Two-one = = One,eight-six = =];
A.[true,true]
B.[false,false]
C.[true,false]
D. Other

9, the following expression runs as a result:

    1. function ShowCase (value) {
    2. Switch (value) {
    3. Case ' A ':
    4. Console.info (' Case A ');
    5. Break
    6. Case ' B ':
    7. Console.info (' Case B ');
    8. Break
    9. Case undefined:
    10. Console.info (' undefined ');
    11. Break
    12. Default
    13. Console.info (' Do not know! ');
    14. }
    15. }
    16. ShowCase (New String (' A '));

A.case A
B.case B
C.do not know
d.undefined

10, the following expression runs as a result:

    1. function ShowCase (value) {
    2. Switch (value) {
    3. Case ' A ':
    4. Console.info (' Case A ');
    5. Break
    6. Case ' B ':
    7. Console.info (' Case B ');
    8. Break
    9. Case undefined:
    10. Console.info (' undefined ');
    11. Break
    12. Default
    13. Console.info (' Do not know! ');
    14. }
    15. }
    16. ShowCase (String (' A '));

A.case A
B.case B
C.do not know
d.undefined

11, the following expression runs as a result:

    1. function isodd (num) {
    2. return num% 2 = = 1;
    3. }
    4. function IsEven (num) {
    5. return num% 2 = = 0;
    6. }
    7. function Issane (num) {
    8. return IsEven (num) | | IsOdd (num);
    9. }
    10. var values = [7,4, ' + ', -9,infinity];
    11. Values.map (Issane);

A.[true, True, True, true, True]
B.[true, True, True, true, false]
C.[true, True, True, False, false]
D.[true, True, False, False, false]

12, the following expression runs as a result:
[Parseint (3,8), parseint (3,2), parseint (3,0)]
a.[3,3,3]
B.[3,3,nan]
C.[3,nan,nan]
D. Other

13, the following expression runs as a result:
Array.isarray (Array.prototype)
A.true
B.false
C. Error
D. Other

14, the following expression runs as a result:
var a = [0];
if ([0]) {
Console.info (A = = true);
}else{
Console.info ("Else");
}

A.true
B.false
C. " Else
D. Other

15, the following expression runs as a result:
[]==[]
A.true
B.false
C. Error
D. Other

16, the following expression runs as a result:
[(' 5 ' +3), (' 5 '-3)]
A.["53", 2]
b.[8,2]
C. Error
D. Other

17, the following expression runs as a result:
1+-+++-+1
A.true
B.false
C. Error
D. Other

18, the following expression runs as a result:
var arr = Array (3);
Arr[0] = 2
Arr.map (function (elem) {return ' 1 ';});
a.[2,1,1]
b.["1", "1", "1"]
C.[2, "1", "1"]
D. Other

19, the following expression runs as a result:
function Sideffecting (arr) {
Arr[0] = arr[2];
}
function Bar (a,b,c) {
c = 10;
sideffecting (arguments);
return a+b+c;
}
Bar (1,1,1);

A.3
b.12
C. Error
D. Other

20, the following expression runs as a result:
var a = 111111111111111110000;
b = 1111;
Console.info (A+B);
a.111111111111111111111
b.111111111111111110000
C.nan
D.infinity

21, the following expression runs as a result:
Ar x = [].reverse;
X ();
A.[]
b.undefined
C. Error
D.window

22, the following expression runs as a result:
Number.min_value>0
A.true
B.false
C. Error
D. Other

23, the following expression runs as a result:
[1<2<3,3<2<1]
A.[true,true]
B.[true,false]
C. Error
D. Other

24, the following expression runs as a result:
2 = = [[[2]]]
A.true
B.false
c.undefined
D. Other

25, the following expression runs as a result:
[3.toString (), 3..toString (), 3...toString ()]
a.["3", Error,error]
b.["3", "3.0", error]
C.[error, "3", error]
D. Other

26, the following expression runs as a result:
(function () {
var x1 =y1 = 1;
})();
Console.info (y1);
Console.info (x1);
a.1,1
B.error,error
C.1,error
D. Other

27, enumerate the problems of IE and FF script compatibility

28, what's wrong with the following function? How to improve?

    1. function Initbuttons () {
    2. var body = document.body,button,i;
    3. for (i =0;i<5;i++) {
    4. button = document.createelement ("button");
    5. button.innerhtml = "button" + i;
    6. Button.addeventlistener ("click", Function (e) {
    7. alert (i);
    8. },false);
    9. Body.appendchild (button);
    10. }
    11. }
    12. Initbuttons ();


29. Write a piece of code that determines the most frequently occurring characters in a string and counts the number of occurrences.

30, what is the difference between the two pieces of code?

    1. SetTimeout (function () {
    2. /* code block */
    3. SetTimeout (arguments.callee,10);
    4. },10);
    5. SetInterval (function () {
    6. /* code block */
    7. },10);


Answer:
1,d
Each element of the map array invokes the defined callback function and returns an array containing the results. ["1", "2", "3"].map (parseint) call Paresint for each element in the array. However, this topic differs from:
function Testfuc (a) {
Return parseint (a);
}
Console.info (["1", "2", "3"].map (TESTFUC));
The title is equal to:
function Testfuc (a,x) {
return parseint (A,X);
}
Console.info (["1", "2", "3"].map (TESTFUC));
The syntax for the callback function in map is as follows: function CALLBACKFN (value, index, array1), you can declare a callback function with up to three parameters. The first parameter is the value of the array element, the second argument is index, an array of array elements so; array1, the array object that contains the element.
Therefore, the title is equivalent to [parseint (1,0), parseint (2,1), parseint (3,2)]
Final return [1, Nan, Nan]

2,a
typeof is used to obtain a variable or expression type, typeof generally can only return the following results:
Number,boolean,string,function (function), object (NULL, Array, object), undefined.
Instanceof Indicates whether a variable is an instance of an object, and Null is a special value of type Object that represents the meaning of a null reference. But null returns an object which is actually an error in the implementation of the original JavaScript,
It is then used by ECMAScript to become the current standard, but we can interpret NULL as a placeholder for an object that does not exist, which is not contradictory, although it is a "justification".
For us developers, be wary of this "language feature." Final return: ["Object", false]

3,a
The POW () method returns the value of the Y-power of X. [3,2,1].reduce (Math.pow); equivalent to:
function Testfuc (x, y) {
Console.info (x + ":" +y);
return Math.pow (x, y);
}
Console.info ([3,2,1].reduce (TESTFUC));
Executes Math.pow (3,2) and Math.pow (2,1), eventually returning 9 and 9.
Note, however, that the parameters of the POW are mandatory, [].reduce (Math.pow), which is equivalent to executing the MATH.POW (), which results in an error.

4,a
string concatenation is performed before the checksum is performed
var val = ' value ';
Console.info (' Value id ' + (val = = = ' value123 ')? ' Something ': ' Nothing ');
will also return something

5,a
The judgment statement is wrapped in the call function immediately, the function inside cannot access the external value of ' world ' name, so typeof name = = ' undefined ' is true, perform the next operation, the final output goodbye Jack

6,d
End = 9007199254740992, start = 9007199254740892 The purpose is to calculate the difference between end and start. However, 2 of the 53-time calculation results due to the accuracy of the problem caused i++ failure.

7,c
The filter is exposed to elements that are not assigned, that is, in arr, the length is 10 but the actual numeric element list is [0, 1, 2, 10], and consequently, an empty array is eventually returned []

8,c
The addition or subtraction of two floating-point numbers will result in a loss of accuracy due to a certain normal data conversion eight-six = 0.20000000000000007.
The decimals in JavaScript is represented by a double-precision (64-bit), consisting of three parts: the character + order + Mantissa, 1/10 in decimal, which can be simply written as 0.1 in decimal, but in binary, He had to write: 0.0001100110011001100110011001100110011001100110011001 ... (Back all 1001 loops). Because the floating-point number has only 52 valid digits, it is rounded off from the 53rd bit. This causes the problem of "floating point precision loss".
The more rigorous approach is (eight-six). TOTOFIEXD (1) or use the Math.Round method to return to integer operations. Determine if two floating-point numbers are equal, or suggest approximation comparisons, such as if ((a) < 1E-10)

9,c
Use the new String () to call a completely new object as the value of the this variable and implicitly return the new object as the result of the call, so Showcase () receives a parameter of string {0: "a"} is not what we think of as "a"

10,a
The variable created directly by invoking string ("a") is the same as "a".
var a= "123" ' just set the variable
B=new String (' 123 ') ' Sets a member
var a= "123";
A.sex=1;
alert (a.sex);//output undefined, because not a member, no this property
B=new String (' 123 ');
B.sex=1;
alert (b.sex);//Output 1, member's properties

11,c
function Issane (num) {
return IsEven (num) | | IsOdd (num);
}
The function determines whether NUM is a positive integer, ' 13 ' is cast to a value 13,-9%2 the result is -1,infinity%2 is Nan

12,d
The final result is [3, NaN, 3];
The parseint () function parses a string and returns an integer. When the value of the parameter radix is 0, or if the parameter is not set, parseint () determines the cardinality of the number based on string.

13,a
Array.prototype for [],array.isarray (a) is a method that determines whether a is an array.
A method that determines whether an object is an array:
1) ES5 function IsArray (), which tests whether an object's internal [[Class]] property is an array:
Arrray.isarray (a);
2) Determine if the object's constructor is an array:
A.constructor = = = Array
3) Create a result string using the object's internal [[Class]] Property:
Object.prototype.toString.call (a)
4) Use the instanceof operator to test whether the object inherits from the array:
(However, because a page's IFRAME does not inherit an iframe from another page, the method is unreliable)
A instanceof Array

14,b
In the IF condition judgment statement relative to the = = Comparison loose, as long as if (n), n is not a null,0,undefined value, will be converted to true. Enter Console.info (A = = True), and eventually return false.

15,b
arrays, which are objects in Javascript, and objects that use the = = comparison are references to comparisons. Simply put, that is, if it is the same object, it is equal, and if it is not the same object, it will be different. Each time you use [] is a new array object, so [] = = [] This statement built two data objects, they are not equal.

16,a
Execute ' 5 ' +3, plus with the concatenation string function, will cast 3 to the string ' 3 ' and ' 5 ' stitching.
Execute ' 5 '-3, minus sign only has the function of numeric arithmetic, therefore will convert ' 5 ' to numerical value, perform 5-3 numerical operation

17,c

18,d
Differentiate assignments and declarations. Although var arr = array (3), a 3-length array is created, but only one element is actually assigned, so the actual length of ARR is 1, that is, only one element that eventually participates in the map, returns [1]

19,d
Follow the steps, no need to be paranoid, the end result is 10+1+10

20,b
JS's exact integer maximum is: Math.pow (2,53)-1 =9007199254740991.
var a = 111111111111111110000,
max = 9007199254740992;
The value of a is greater than the maximum integer precision that JavaScript can represent, so adding to any number will result in distortion.
In-depth understanding can be viewed http://www.zhihu.com/question/24423421

21,c
The correct invocation method is X.call ([])

22,b
The minimum value represented by Number.min_value is 5e-324,min_value, which is not a negative minimum, but a number closest to 0, so number.min_value>0.
The negative minimum value can be expressed using-number.max_value.

23,a
1&LT;2, which returns True, executes true<3, which forces the conversion of true to 1,1<3 and eventually returns true.
3<2, returns FALSE, executes false<1, forces false to 0,0<1, and eventually returns true.

24,a
Using A==B to determine whether a and B objects are equal, you can cast a B object to the type of a object, that is, execute 2 = = [[[2]]], and implicitly call parseint ([[[[[[[[[]]]]) to force [[[[]]] to convert to a number base, which is 2,2==2, and

25,c
The ToString (a) in number, which converts the value to a-binary. However, when a defaults, the default is converted to decimal.
The general use method is: var n = 3;3.tostring ();
Perform 3.toString () because 3 is only a numeric variable and is not a number instance, so for 3 you cannot call the # method directly. While performing 3. ToString (), which forces 3 to be converted to a numeric instance, can be interpreted, and output 3 can also be used (3). ToString ().

26,c
Execute within the immediate call function, var x1 =y1 = 1; Create local variable x1 and global variable y1. Attempting to access variables inside the function outside of the function will result in an error.

27,
Enumerate the issues of IE and FF scripting compatibility
(1) window.event
Represents the current event object, IE has this object, FF has no
(2) Get event source
IE uses srcelement to get the event source, while FF gets the event source with target
(3) adding, removing events
IE:element.attachEvent ("onclick", function)
Element.detachevent ("onclick", function)
FF:element.addEventListener ("click", Function,true)
Element.removeeventlistener ("click", Function,true)

28,
The code given in the topic, in addition to the problem of addeventlistener incompatible with IE browser, the most prominent problem is:
Although a button with a value of button+i is displayed on the page, clicking any of the buttons will eventually show 5.
To click on the relevant button to eject the corresponding 1,2,3,4,5 value, you need to understand the closure principle implementation and use the immediate callback function. The modified code is as follows:

  1. function Initbuttons () {
  2. var body = document.body,button,i;
  3. for (i =0;i<5;i++) {
  4. (function (i) {
  5. button = document.createelement ("button");
  6. button.innerhtml = "button" + i;
  7. Button.addeventlistener ("click", Function (e) {
  8. alert (i);
  9. },false);
  10. Body.appendchild (button);
  11. }) (i);
  12. }
  13. }
  14. Initbuttons ();


involves binding and assigning merit to the difference. At run time, a scope is entered, and JavaScript allocates a slot (slot) in memory for each variable bound to that scope. function, the variable document.body,button,i is created, so the function assigns a "slot" to each variable when the function body (the button is created and the button is bound to the event) is called. In each iteration of the loop, the loop body assigns a closure to the nested function. We might understand that the function stores the value of the variable i when the nested function was created. But in fact, he's storing a reference to I. Since the value of the variable i is changed every time the function is created, the reference to the variable i is ultimately seen inside the function. Closures store references to external variables rather than values.
A function expression that is called immediately is an indispensable way to address the lack of block-level scope for JavaScript.
For an in-depth understanding, you can view the effective JavaScript 13th: Create a local scope with an immediately invoked function expression

29, match two algorithms with regular method and regular expression

  1. /* Write a section of code. Determine the most frequently occurring string in a string, and count the number of occurrences */
  2. function Togetthemostcharsbyarray (s) {
  3. var r={};
  4. for (Var i=0;i<s.length;i++) {
  5. if (!r[s]) {
  6. R[s] = 1;
  7. }else{
  8. r[s]++;
  9. }
  10. }
  11. var max = {
  12. "Value": s[0],
  13. "num": r[s[0]]
  14. };
  15. for (var n in R) {//object uses the IN keyword because there is no length
  16. if (r[n]>max.num) {
  17. Max.num = R[n];
  18. Max.value = n;
  19. }
  20. }
  21. return Max;
  22. }
  23. function Togetthemostcharsbyregex (s) {
  24. var a = S.split (");
  25. A.sort ();
  26. s = A.join (");
  27. var regex =/(\w) \1+/g;//\1 represents duplicates
  28. var max = {
  29. "Value": s[0],
  30. "num": 0
  31. };
  32. S.replace (Regex,function (A, b) {
  33. if (Max.num < a.length) {
  34. Max.num = A.length;
  35. Max.value= b;
  36. }
  37. });
  38. return Max;
  39. }
  40. var test = "Efdfssssfrhth";
  41. Console.info ("Using the general method, the most frequently occurring string is:" +togetthemostcharsbyarray (Test). value+ ", Occurrences:" +togetthemostcharsbyarray (Test). NUM);
  42. Console.info ("string matching, most occurrences of the string is:" +togetthemostcharsbyregex (Test). value+ ", Occurrences:" +togetthemostcharsbyregex (Test) . num);


30,
The JavaScript engine is single-threaded
The JavaScript engine is event-driven.
Both settimeout and setinterval add a pending time to the event queue, settimeout fires only once, and setinterval is a cyclic trigger.

    1. SetTimeout (function () {
    2. code block
    3. SetTimeout (arguments.callee,10);
    4. },10);
    5. The previous code allows the settimeout loop to trigger. However, the execution of this block of code suspends the time, so two execution times are greater than 10 milliseconds
    6. SetInterval (function () {
    7. /* code block */
    8. },10);


And the previous code, is automatically in 10 when the event hangs, so two times the interval of the event will be less than or equal to 10 milliseconds.
When a thread is blocked at an event, either using SetInterval or settimeout waits for the current event to be processed before it can be executed.
To further understand JavaScript threading blocking, you can view the topics mentioned in http://www.cnblogs.com/0603ljx/p/4387628.html.

30 JavaScript questions and answers that you "can't do all"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.