闭包题目练习
2017-10-05 本文已影响0人
海山城
1.如下代码输出多少?如果想输出3,那如何改造代码?
var fnArr = [];
for (var i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
};
}
console.log( fnArr[3]() )
输出为10
想输出3,可做如下改造
//方法一
var fnArr = [];
for (var i = 0; i < 10; i ++) {
(function(i){
fnArr[i] = function(){
return i
};
})(i)
}
console.log( fnArr[3]() )
//方法二
var fnArr = [];
for (var i = 0; i < 10; i ++) {
fnArr[i] = (function(j){
return function(){
return j
}
})(i)
}
console.log( fnArr[3]() )
//方法三
var fnArr = []
for (let i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
}
}
console.log( fnArr[3]() )
2.封装一个 Car 对象
var Car = (function(){
var speed = 0;
//补充
return {
setSpeed: setSpeed,
getSpeed: getSpeed,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.setSpeed(30)
Car.getSpeed() //30
Car.speedUp()
Car.getSpeed() //31
Car.speedDown()
Car.getSpeed() //30
实现
var Car = (function(){
var speed = 0;
function setSpeed(val){
speed = val
return speed
}
function getSpeed(){
console.log(speed)
return speed
}
function speedUp(){
speed++
}
function speedDown(){
speed--
}
return {
setSpeed: setSpeed,
getSpeed: getSpeed,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.setSpeed(30)
Car.getSpeed() //30
Car.speedUp()
Car.getSpeed() //31
Car.speedDown()
Car.getSpeed() //30
3.如下代码输出多少?如何连续输出 0,1,2,3,4
for(var i=0; i<5; i++){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
}
输出5个delayer:5
改造
//方法一
for(var i=0; i<5; i++){
(function(i){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
})(i)
}
//方法二
for(var i=0; i<5; i++){
setTimeout((function(i){
return function(){
console.log('delayer:' + i )
}
})(i), 0)
}
//方法三
for(let i=0; i<5; i++){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
}
4. 如下代码输出多少?
function makeCounter() {
var count = 0
return function() {
return count++
};
}
var counter = makeCounter()
var counter2 = makeCounter();
console.log( counter() ) // 0
console.log( counter() ) // 1
console.log( counter2() ) // ?
console.log( counter2() ) // ?
最后两个console.log输出的也是0和1。counter和counter2是两个互不影响的函数
5.补全代码,实现数组按姓名、年纪、任意字段排序
var users = [
{ name: "John", age: 20, company: "Baidu" },
{ name: "Pete", age: 18, company: "Alibaba" },
{ name: "Ann", age: 19, company: "Tecent" }
]
users.sort(byField('age'))
users.sort(byField('company'))
实现
var users = [
{ name: "John", age: 20, company: "Baidu" },
{ name: "Pete", age: 18, company: "Alibaba" },
{ name: "Ann", age: 19, company: "Tecent" }
]
function byField(field){
return function(user1, user2){
return user1[field] > user2[field]//因为field是字符串,所以不能用.来访问
}
}
users.sort(byField('age'))
console.log(users)
6.写一个 sum 函数,实现如下调用方式
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
实现
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
function sum(a){
return function(b){
return a + b
}
}