JS面試題
阿新 • • 發佈:2017-11-08
urn settime 銷毀 dom set ons -1 執行 blog
for(var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }); } for(var i = 0; i < 5; i++) { (function(i) { setTimeout(function() { console.log(i); }); })(i); }
結果:
5
5
5
5
5
0
1
2
3
4
setTimeOut()會在所有可執行函數執行後在執行。
匿名函數會立即執行。
function foo1() { var value = 1 + 1 return value; } //JS中如果一個語句以[(/+-開頭,就有可能和上一句加在一起解析 function foo2() { return { bar: ‘hello‘ }; } //return 後會自動添加分號,不管下一條語句是什麽 console.log(foo1()); console.log(foo2());
結果:
2
undefined
(function() { var a=b= 3 ; })(); //a是局部變量,匿名函數運行完畢直接銷毀,b聲明為全局變量,會一直存在。 console.log("a defined? " + (typeof a !== ‘undefined‘)); console.log("b defined? " + (typeof b !== ‘undefined‘)); console.log(b); console.log(typeof a);
結果:
a defined? false
b defined? true
3
undefined
var object = { foo: "bar", func: function() { var self = this; console.log(this); console.log("outer func: this.foo = " + this.foo); console.log("outer func: this.foo = " + self.foo); (function() { console.log("inner func: this.foo = " + global.foo); console.log("inner func: this.foo = " + self.foo); })(); } }; //global 是 javascript 運行時所在宿主環境提供的全局對象,是一個 Object。目前來說最常見的宿主環境是瀏覽器和 nodejs,瀏覽器暴露了一系列操作 DOM, Location, History 等 Api 供 Js 調用(即 window 對象)而 nodejs 裏則沒有瀏覽器裏的 DOM 等,可以運行 for (var i in global){console.log(i)} 查看這個全局對象提供的方法,如 process, buffer 這些 nodejs 的資源。 //匿名函數的this指的是global對象(nodejs環境下)瀏覽器環境下就是window對象 object.func();
結果:
{ foo: ‘bar‘, func: [Function: func] }
outer func: this.foo = bar
outer func: this.foo = bar
inner func: this.foo = undefined
inner func: this.foo = bar
var scope = "global"; function func() { console.log(scope); var scope = "local"; } //變量提升 undefined func();
console.log((function f(n) { return ((n > 1) ? n * f(n-1) : n); })(10)); //階乘 匿名函數 //結果是10的階乘的結果 console.log((function (n) { return n; })(8)) //匿名函數 第二個括號是函數參數
console.log("1" + 1); //字符前加+ -會把它變成number類型 console.log(1 + "2" + "2"); //122 console.log(1 + +"2" + "2"); //32 console.log(1 + -"1" + "2"); //02 console.log(+"1" + "1" + "2"); //112 console.log("A" - "B" + "2"); //NaN2 console.log("A" - "B" + 2); //NaN +2 還是NaN console.log("A" - "B"); //NaN //JS在進行這種運算時 僅僅會在2個值相加時優先推斷為string類型 其它情況下(比如“-”。“*”。“/”)都默覺得number型運算。
//判斷一個方法是不是數組 //方法一 function isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; } //方法二 function isArray(obj) { return obj.__proto__ === Array.prototype; } //方法三(ES5) Array.isArray(obj);
function Example() { getName = function() { console.log(1); }; return this; } Example.getName = function() { console.log(2); }; Example.prototype.getName = function() { console.log(3); }; console.log(typeof Example); //function console.log(typeof Example()); //object Example.getName(); //函數的方法 Example().getName(); //對象的方法 new Example.getName(); //new 一個函數的方法 結果還是2 new Example().getName(); //原型對象方法,實例共享時使用
結果:
function
object
2
1
2
3
JS面試題