Open yunyu950908 opened 6 years ago
i
var fnArr = [];
for (var i = 0; i < 10; i++) {
let temp = i ;
fnArr[i] = function () {
return temp;
};
}
console.log(fnArr[3]()); //3
i
和外部变量i
不同,原理类似方法一 var fnArr = [];
for (var i = 0; i < 10; i++) {
!function (i) {
fnArr[i] = function () {
return i;
}
}(i)
}
console.log(fnArr[3]()); //3
let
创建作用域块,i只在本轮循环有效 var fnArr = [];
for (let i = 0; i < 10; i++) {
fnArr[i] = function () {
return i;
};
}
console.log(fnArr[3]()); //3
var Car = (function () {
var speed = 0;
function setSpeed(s) {
return speed = s
}
function getSpeed() {
return console.log(speed)
}
function accelerate() {
return speed += 10
}
function decelerate() {
return speed >= 0 ? speed -= 10 : speed
}
function getStatus() {
return console.log(speed > 0 ? "running" : "stop")
}
return {
setSpeed: setSpeed,
getSpeed: getSpeed,
accelerate: accelerate,
decelerate: decelerate,
getStatus: getStatus,
speed: "error"
}
})()
Car.setSpeed(30);
Car.getSpeed(); //30
Car.accelerate();
Car.getSpeed(); //40;
Car.decelerate();
Car.decelerate();
Car.getSpeed(); //20
Car.getStatus(); // 'running';
Car.decelerate();
Car.decelerate();
Car.getStatus(); //'stop';
//Car.speed; //error
var a = 1;
setTimeout(function () {//在闹钟下压张纸,当前队列结束后,再看这张纸上的队列(异步)
a = 2;
console.log(a);//2
}, 0);
var a;
console.log(a);//1
a = 3;
console.log(a);//3
setTimeout
异步操作,脱离栈进入event loop循环等待,主栈内的非异步执行完再推入栈内执行回调
var flag = true;
setTimeout(function () { //异步,但是无操作,flag始终为true,while无限循环,无法结束当前栈内操作
flag = false;
}, 0)
while (flag) {} //flag为true,无限循环
console.log(flag); //无输出
for(var i=0;i<5;i++){
setTimeout(function(){
console.log('delayer:' + i ); // 在 0 1 2 3 4 后输出5次 delayer:5
}, 0);
console.log(i); // 0 1 2 3 4
}
for (var i = 0; i < 5; i++) {
!function (i) {
setTimeout(function () {
console.log('delayer:' + i);
}, 0);
}(i)
console.log(i);
}
function getStyle(e) {
//IE不支持window.getComputedStyle(),支持element.currentStyle();
return e.getComputedStyle() ? window.getComputedStyle(e) : e.currentStyle
}
let trueWidth = getStyle(e).width;
let trueHeight = getStyle(e).height;
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
ASCII字母
数字
~!@#$&*()=:/,;?+'
ASCII字母
数字
~!*()'
所以encodeURIComponent比encodeURI编码的范围更大
encodeURIComponent会把 http:// 编码成 http%3A%2F%2F 而encodeURI却不会。
encodeURI
和encodeURIComponent
的区别在于前者被设计来用于对完整URL
进行URL Encode
,于是URL
中的功能字符,比如&
, ?
, /
, =
等等这些并不会被转义;而后者被设计来对一个URL
中的值进行转义,会把这些功能字符也进行转义。
let myURL = 'https://www.google.com/#q=javascript';
let simpleURL = encodeURI(myURL); //"https://www.google.com/#q=javascript"
let completeURL = encodeURIComponent(myURL); //https%3A%2F%2Fwww.google.com%2F%23q%3Djavascript"
function isAndroid() {
return /Android/.test(navigator.userAgent);
}
function isIphone() {
return /iPhone/.test(navigator.userAgent);
}
function isIpad() {
return /iPad/.test(navigator.userAgent);
}
function isIOS() {
return /(iPad)|(iPhone)/i.test(navigator.userAgent);
}
题目1: 下面的代码输出多少?修改代码让
fnArr[i]()
输出i
。使用 两种以上的方法