Key to 'JavaScript Puzzlers'(2)
Continue.
3.What is the result of this expression? (or multiple ones)
1 | [ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ] |
A an error
B [9,0]
C [9,NaN]
D [9,undefined]
See more information about Array.prototype.reduce()> The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
reduce() accept 2 arguments:reduce(callback,initialValue),this callback function will get 4 arguments:
callback(accumulator,currentValue,currentIndex,array) > accumulator > > The accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.) > > currentValue > > The current element being processed in the array. > > currentIndex > > The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. > > array > > The array reduce was called upon.
For example,use 1
2
3[1,2,3,4,5].reduce(function(a,b){
return a+b
})
It returned 15.
First callback function got (1,2) returned 3,then the 2nd callback function got (3,3) returned 6.The 3rd callback got (6,4) returned 10,the 4st callback got (10,5) returned 15,the finally result.
Math.pow() will calculate power value.It accept 2 arguments,like Math.pow(base,exponent)
It's equal to baseexponent
In this problem,[1,2,3].reduce(Math.pow) means that:
step1: Math.pow got (1,2) returned 1
step2: Math.pow got (1,3) returned 1
Finally it got 1.
But the 2nd array's item is []
reduce() method need an intial value at least,so it will throw an error:
TypeError: Reduce of empty array with no initial value
So this problem's correct answer is A
4.What is the result of this expression? (or multiple ones)
1 | var val = 'smtg'; |
A Value is Something
B Value is Nothing
C NaN
D Other
This is a trick question.The correct is D
The operator '+' will calculate first because it has higher precedence.
That expression equal to 1
console.log('Value is true'? 'Something':'Nothing');
An string expression like 'true' in condition,So it will print 'Something'
5.What is the result of this expression? (or multiple ones)
1 | var name = 'World!'; |
A Goodbye Jack
B Hello Jack
C Hello undefined
D Hello World
This a question about "Hoisting".The 'var' will hoisting in the function scope.
So the code will be this: 1
2
3
4
5
6
7
8
9
10var name = 'World!';
(function () {
var name
if (typeof name === 'undefined') {
name = 'Jack';
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();
For if (typeof name === 'undefined'),it will find name from scope chain,so this 'name' is declared in anonymous function: var name
'var name' means that name is undefined,so condition of 'if' is true,then name is declared 'Jack'.
Hence,printed 'Goodbye Jack'
Do rest tomorrow