【Web前端问题】今日面试题,有一定难度。求指导
求解答 4题 5题
回答:
// 第四题var mathLib = {
pi: 3.14,
area: function(r) {
return this.pi * r * r
},
circumference: function(r) {
return this.pi * r * 2
}
}
Function.prototype.after = function() {
var _self = this
return function() {
var result = _self.apply(this, arguments)
return typeof result === 'number' ? result.toFixed(5) : result
}
}
for (var key in mathLib) {
if (typeof mathLib[key] !== 'function') continue
mathLib[key] = mathLib[key].after()
}
console.log(mathLib.area(1.5))
console.log(mathLib.circumference(1))
// 第五题
var generator = (function() {
var arr = []
var gen = function(string) {
arr = string.split('')
return gen
}
gen.next = function() {
return arr.shift()
}
return gen
})()
var mygeo = generator('boomerang')
console.log(mygeo.next())
console.log(mygeo.next())
console.log(mygeo.next())
var mygeo = generator('toon')
console.log(mygeo.next())
console.log(mygeo.next())
链接: demo
回答:
call/apply/bind
替换pi
- 都说闭包了,
next
改变持有的变量就完了。
回答:
- 用 toFixed(5) ?
- 代码:
function generator(str) { let i = 0
return {
next() {
return str[i++]
}
}
}
以上是 【Web前端问题】今日面试题,有一定难度。求指导 的全部内容, 来源链接: utcz.com/a/142191.html