1.作用域
(function(){
var a=b=5;
})();
console.log(b);//输出5,开启严格模式会报错
2.变量提升
function test(){
console.log(a);
console.log(foo());
var a=1;
function foo(){
return 2;
}
}
test();//输出undefined 2
//相当于
function test(){
var a;
function foo(){
return 2;
}
console.log(a);
console.log(foo());
a=1;
}
test();
3.this指向
var fullname='name1';
var obj={
fullname:'name2',
prop:{
fullname:'name3',
getFullname:function(){
return this.fullname;
}
}
};
console.log(obj.prop.getFullname());
var test=obj.prop.getFullname;
console.log(test());//输出name3 name1
//使用call,apply强制转换上下文环境,最后一行替换为:
console.log(test.call(obj.prop));//输出name3 name3
4.数据类型
console.log(typeof null);
console.log(typeof {});
console.log(typeof []);
console.log(typeof undefined);
//输出object object object undefined
//测试变量是否为数组用instanceof Array
5.时间循环
function printing(){
console.log(1);
setTimeout(function(){console.log(2);},1000);
setTimeout(function(){console.log(3);},0);
console.log(4);
}
printing();//输出1 4 3 2
6.setTimeout延迟执行
for(var i=0;i<5;i++){
setTimeout(function(){
console.log(i);
},1000*i);
}// 直接输出5,每隔一秒输出5 5 5 5
7.闭包
for(var i=0;i<5;i++){
(function(i){
setTimeout(function(){
console.log(i);
},1000*i);
})(i);//直接输出0,每隔一秒输出1 2 3 4
}
8.定时器原理
for(var i=0;i<5;i++){
setTimeout(function(){
console.log(i);
},1000);
}//1秒之后输出5 5 5 5 5
9.静态作用域
var value=1;
function foo(){
console.log(value);
}
function bar(){
var value=2;
foo();
}
bar();//输出1
10.sort()排序
var arr=[4,3,5,2,1];
result1=arr.sort(function(a,b){
return a-b;
});
console.log(arr);//输出[1,2,3,4,5]
console.log(result1);//输出[1,2,3,4,5]
result2=arr.sort(function(a,b){
return b-a;
});
console.log(arr);//输出[5,4,3,2,1]
console.log(result1);//输出[5,4,3,2,1]
console.log(result2);//输出[5,4,3,2,1]
网友评论