Some JS problems and parsing 1)
["1","2","3"].map(parseInt);
What is the result of the operation?
a.["1", "2", "3"]b.[1,2,3]c.[0,1,2]d. Other
Analysis:
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 the [parseInt(1,0),parseInt(2,1),parseInt(3,2)]
final return [1, Nan, Nan].
parseint ():
parseInt(string, radix);
Accepts two parameters string
and radix
.
String
A string of ' class number ' string to parse.
(the value to parse.) If string is not a string, then it's converted to one. Leading whitespace in the string is ignored.)
Radix
Parses the cardinality setting of a string, with a range of values between 2~36 [closed interval].
(An integer between 2 and represents, the radix (the base in mathematical numeral systems) of the above Menti oned string. Specify for the decimal numeral system commonly used by humans. Always specify the parameter to eliminate reader confusion and to guarantee predictable. Different implementations produce Different results when a radix was not specified.)
From the definition of parseint a convenient understanding, the first parameter of parseint must be less than the second parameter, of course, they are the number of string comparison. Otherwise the result is Nan.
An accident: When radix
the value is 0, it is equivalent to the default parseint (string) and not radix
. Eg:
parseInt(1,0);//相当于parseInt(1); ->1parseInt(0123,0);//相当于parseInt(0123); ->83
2)
[typeof null, null instanceof Object]
What is the result of the operation?
A.["Object", false]b.[null,false]c.["Object", True]d. Other
Analysis
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 object, which is actually an error in the implementation of the original JavaScript and then used by ECMAScript as the current standard, but we can interpret NULL as a placeholder for an object that does not exist, so it is not contradictory, although it is a "justification".
For us developers, be wary of this "language feature." Final return: ["Object", false]
3) [[3,2,1].reduce (Math.pow), [].reduce (MATH.POW)] Run the result is?
A. Error B. [9,0] C.[9,nan]d.[9,undefined]
Analysis
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));
Execution Math.pow(3,2)
and Math.pow(9,1)[].reduce(Math.pow)
, equivalent to execution, Math.pow();
can result in an error.
Here to introduce the next
arr.reduce(callback[, initialValue])
The
International practice, official explanation:
Parameters Allback Function to execute on each value in the array, taking four arguments: previousvaluethe value previously Returned in the last invocation of the callback, or InitialValue, if supplied. CurrentValue The current element is being processed in the array. Index The index of the current element is being processed in the array. Array The array reduce was called upon. InitialValue Optional. Object to use as the first argument to the first call of the callback.
4) The following code runs as follows:
var name = ‘World‘;(function(){ if(typeof name === ‘undefined‘){ var name = "Jack"; console.info(‘Goodbye ‘+ name); }else{ console.info(‘Hello ‘ + name); }})();
A.goodbye Jackb.hello jackc.goodbye Undefinedd.hello undefined
Analysis
A
There is something in the JS function called "declaration ahead". So select a.
5) The following code runs as follows:
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]
Analysis
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 []
Another chance to explain the JS function, huh?
arr.filter(callback[, thisArg])
International practice, official explanation:
Parameters callback Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise. Thisarg Optional. Value to use as this when executing callback.
Simply come on. Is the filter that returns the value of callback (value) to true in arr. Over
6) The following code runs the result:
var two = 0.2;var one = 0.1;var eight = 0.8;var six = 0.6;[two -one == one,eight- six == two];
A.[true,true]b.[false,false]c.[true,false]d. Other
Analysis
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)
It is worth noting that 0.2-0.1 is ==0.1.
7) The following code runs as a result:
function showCase(value){ switch(value){ case ‘A‘: console.info(‘Case A‘); break; case ‘B‘: console.info(‘Case B‘); break; case undefined : console.info(‘undefined‘); break; default: console.info(‘Do not know!‘); }}showCase(new String(‘A‘));
A.case AB. Case BC. Do not knowd.undefined
Analysis
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"
But, obviously, at this point the new string (' a ') = = ' A ', although new is a string object.
var a = new String (' a '); ->a = = String {0: "A", length:1, [[Primitivevalue]]: "a"}a = = ' a '; -True
From the above we can know, even if the title of the showCase(new String(‘A‘));
change var a = new String(‘A‘);showCase(a);
, it passed in is still an String{0:‘A‘...}
object. The result is still C.
8) The following expressions run as follows:
Array.isArray(Array.prototype)
A.trueb.falsec. Error d. Other
Analysis
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 array: (but because a page's IFRAME does not inherit an iframe from another page, the method is unreliable)
a instanceof Array
9) [] = = [] The result of the operation is:
A.trueb.falsec. Error d. Other
Analysis
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.
So the question is, how do you judge two arrays to be equal?
Lodash is compared with _.isequal (value, other, [Customizer], [Thisarg]).
10)
[3.toString(),3..toString(),3...toString()]
The results of the operation are:
a.["3", error,error]b.["3", "3.0", Error]c.[error, "3", error]d. Other
Analysis
C
toString(a)
number can be converted to a value of a binary. However, when a defaults, the default is converted to decimal, the general use is:
var n = 3;n.toString();
Executes 3.toString()
because 3 is only a numeric variable and is not a number instance, so for 3 it is not possible to call the # method directly. Execution will 3..toString()
force 3 to be converted to a numeric instance, so it can be interpreted, and output ' 3 ' is also available (3).toString()
.
11) List of IE and FF script compatibility issues: Analysis
Enumerate the issues of IE and FF scripting compatibility
- (1) window.event represents the current event object, IE has this object, FF does not have
- (2) Get event source IE uses srcelement to get event source, while FF gets 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)
11) What is the problem with the following function? How to improve?
function initButtons(){ var body = document.body,button,i; for(i =0;i<5;i++){ button = document.createElement("button"); button.innerHTML = "Button" + i; button.addEventListener("click",function(e){ alert(i); },false); body.appendChild(button); } } initButtons();
Analysis
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:
function initButtons(){ var body = document.body,button,i; for(i =0;i<5;i++){ (function(i){ button = document.createElement("button"); button.innerHTML = "Button" + i; button.addEventListener("click",function(e){ alert(i); },false); body.appendChild(button); })(i); } } 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.
So, we're going to say a little bit about the closure in JS.
Closed Package
Given that this space may be a bit long, put in another closures file.
12) write a piece of code that determines the most frequently occurring characters in a string and counts the number of occurrences. Analysis
/* Write a section of code. Determine the most frequently occurring string in a string and count the number of occurrences *//General method function Togetthemostcharsbyarray (s) {var r={}; for (var i=0;i< s.length;i++) {if (!r[s[i]]) {R[s[i]] = 1; }else{r[s[i]]++; }} var max = {"value": s[0], "num": R[s[0]]}; for (var n in R) {if (r[n]>max.num) {max.num = R[n]; Max.value = n; }} return max; }//Use regular method function Togetthemostcharsbyregex (s) {var a = S.split ('); A.sort (); s = A.join ("); var regex =/(\w) \1+/g; \1+ represents the duplicated var max = {"value": s[0], "num": 0}; S.replace (A, b) {//a is a duplicate of String:eg: ' AAA ', a duplicate letter char:eg: ' A '; if (Max.num < a.length) {max.num = A.length; Max.value= b; } }); return Max; } var test = "Efdfssssfrhth "; Console.info ("Using the general method, the most frequently occurring string is:" +togetthemostcharsbyarray (Test). value+ ", Occurrences:" +togetthemostcharsbyarray (Test). NUM); Console.info ("string matching, most occurrences of the string is:" +togetthemostcharsbyregex (Test). value+ ", Occurrences:" +togetthemostcharsbyregex (Test) . num);
Note that the regular judgment here repeats the letter, leaving a position to introduce the regular ...
13) What is the difference between the two pieces of code?
//1. setTimeout(function(){ /*代码块*/ setTimeout(arguments.callee,10); },10); //2. setInterval(function(){ /*代码块*/ },10);
Analysis
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.
setTimeout(function(){ //代码块 setTimeout(arguments.callee,10); },10); //上段代码可使得setTimeout循环触发。但是,执行完这段代码块才挂起时间,所以两次执行时间会大于10ms setInterval(function(){ /*代码块*/ },10); //而上段代码,是自动在10ms的时候挂上这个事件,所以两次事件的相隔会小于等于10ms。
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.
By this problem, we introduce the following topic:
Performance Testing and calculation of code uptime using the console
14) What does the following code pop up?
alert(1&&2);
Analysis
A && B: If A is true, return B, if A is false, return a. So pop up 2.
Similarly, | | Before the front is true, the preceding is a dummy fetch.
Javascriptの you ask my answer (update ...)