for (var i = 1; i <= 5; i++) {
setTimeout( function timer() {
console.log(i+'m');
}, 1000 );
}
以上輸出 5個(gè)6
如何做到輸出每個(gè)數(shù)呢?
①如下
for (let i = 1; i <= 5; i++) {
setTimeout( function timer() {
console.log(i+'m');
}, 1000 );
}
②如下
for (var i = 1; i <= 5; i++) {
(function(i){
setTimeout( function timer() {
console.log(i+'m');
}, 1000 );
})(i)
}
使用var或是非對象內(nèi)部的函數(shù)表達(dá)式內(nèi),可以訪問到存放當(dāng)前函數(shù)的變量;在對象內(nèi)部的不能訪問到。
原因也非常簡單遥缕,因?yàn)楹瘮?shù)作用域鏈的問題,采用var的是在外部創(chuàng)建了一個(gè)fn變量宵呛,函數(shù)內(nèi)部當(dāng)然可以在內(nèi)部尋找不到fn后向上冊作用域查找fn通砍,而在創(chuàng)建對象內(nèi)部時(shí),因?yàn)闆]有在函數(shù)作用域內(nèi)創(chuàng)建fn,所以無法訪問
解如下題:
function fun(n,o) {
console.log(o)
return {
fun:function(m){
return fun(m,n);
}
};
}
var a = fun(0); a.fun(1); a.fun(2); a.fun(3);//undefined,?,?,?
var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
var c = fun(0).fun(1); c.fun(2); c.fun(3);//undefined,?,?,?
//問:三行a,b,c的輸出分別是什么封孙?
//a: undefined,0,0,0
//b: undefined,0,1,2
//c: undefined,0,1,1
function Animal() {
this.name = "Animal";
this.showName = function() {
console.log(this.name);
};
}
function Cat() {
this.name = "Cat";
this._super = Cat.prototype;
this.showName1 = function() {
console.log(this.name);
};
this.showName2 = function() {
console.log(this.name);
};
this.showName3 = function() {
console.log(this._super.name + "=>" + this.name);
};
}
Cat.prototype = new Animal();
var cat = new Cat();
console.log(cat instanceof Animal); //true
cat.showName1(); //"Cat"
cat.showName2.call(Cat.prototype); //"Animal"
cat.showName3(); //"Animal" => "Cat"
編寫一個(gè)程序?qū)?shù)組扁平化去并除其中重復(fù)部分?jǐn)?shù)據(jù)迹冤,最終得到一個(gè)升序且不重復(fù)的數(shù)組:
var arr = [[1,2,2],[3, 4, 5, 5],[6, 7, 8, 9,[11,12,[12,13,[14]]]],10];
=>
var res= [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
function copeArray(initArray){
var result = [];
result = delayering(initArray);
console.log(quickSort(result));
}
var quickSort = function(){
var result = [];
var arr = arguments[0];
if(arr.length<=1){
return arr;
}
var middleIndex = Math.floor(arr.length/2);
var minddleItem = arr.splice(middleIndex,1);
var leftItem = [];
var rightItem = [];
arr.map((item,index)=>{
if(item<minddleItem){
leftItem.push(item)
}else{
rightItem.push(item);
}
})
return quickSort(leftItem).concat(minddleItem).concat(quickSort(rightItem))
}
var delayering = function(){
var result = [];
var arr = arguments[0];
arr.map((item,index)=>{
if(Array.isArray(item)){
var temp = delayering(item);
temp.map((item,index)=>{
if(result.indexOf(item)===-1){
result.push(item)
}
})
}else{
if(result.indexOf(item)===-1){
result.push(item);
}
}
})
return result ;
}
閉包實(shí)現(xiàn)單例
var GetInstance =(function (name,age){
var person;
function Person(){
this.name = name;
this.age = age;
}
function getInst(){
debugger;
if(person !=null){
return person;
}else{
person = new Person();
return person;
}
}
Person.prototype.showName = function(){
console.log('name:'+this.name+','+this.age);
}
return getInst;
})()