qietingfengdeyanse的專欄
1.what is the value of foo?
var foo = 10 + '20'; // '1020'
2.How would you make this work?
add(2,5); // 7
add(2)(5); // 7
第一個就沒必要解釋了,主要是第二個
function add(x){
var sum = x;
var subFun = function (y){
sum += y;
return subFun;//這裡之所以要返回subFun是為了更多的鏈式操作 比如add(2)(5)(3)...
}
return subFun; //執行add(2)將2儲存在sum裡面並且返回subFun方法供(5)執行。
}
3.What value is returned from the following statement?'i'm a lasagna hog'.split("").reverse().join("");
//注:.split("")裡面沒有空格 如果把空字串 ("") 用作 separator,那麼 stringObject 中的每個字元(包括空格)之間都會被分割。所以結果是"goh angasal a m'i"
'i'm a lasagna hog'.split(" ").reverse().join(" "); //結果則是'hog lasagna a i'm'
4.var a = [] 和 var a = new Array()效能的區別;(其實就沒有區別)
5.what is the outcome of the tow alerts below?
var foo = "Hello";
(function(){
var bar =" World";
alert(foo+bar); // Hello World
})();
alert(foo + bar); // 報錯 bar undefined
6.What is the value of foo.x
?
var foo = {n:1};
var bar = foo;
foo.x = foo = {n:2};
/**
*個人總結這個題主要考了三個重點,一是引用賦值,二是js計算符的優先順序,三是賦值表示式結合性
*var foo = {n:1};var bar = foo;所以這兩行的結果是物件foo和bar存的都是同一個物件{n:1}的地址,關鍵在於第三行。由JS運算子的優先順序可以看出物件的屬性訪問
*符'.'在這一行的優先順序最高,所以foo.x最先計算,存下的是對{n:1}這個物件的X屬性的引用。而由於JS賦值表示式是右結合,所以第三行就相當於是
*foo.x = ( foo = {n:2} ),也就是先進行foo = {n:2}這個賦值,所以此時的foo已經指向了{n:2}這個物件,再執行foo.x = foo,也就相當於給{n:1}這個物件的X屬性賦值
*為{n:2},整個過程bar都指向的{n:1}這個物件,所以bar最終結果是{n:1,X:{n:2}},而foo為{n:2}。
**/
7.What dose the following code print?
1️⃣
console.log('one');
setTimeout(function()
{
console.log('two');
},0);
console.log('three'); // one three two
2️⃣
function foo(){
console.log('first');
setTimeout(function(){
console.log('second');
},5);
}
for(var i = 0; i < 1000; i++){
foo();
}
// 結果是全部列印first之後再列印的second。
//其實就是Js的單執行緒