var a = ?; if (a == 1 && a == 2 && a == 3) { console.log(1) } // answer1 a = console.log(1) // answer2 var a = { num: 0 } a.valueOf = () => ++a.num if (a == 1 && a == 2 && a == 3) { console.log(1) } // answer3 Object.defineProperty(window, 'a', { get() { returnthis.value = this.value ? ++this.value : 1 } }) if (a == 1 && a == 2 && a == 3) { console.log(1) }
Number.prototype.add = function (i = 0) { returnthis.valueOf() + i } Number.prototype.minus = function (i = 0) { returnthis.valueOf() - i } var result = (5).add(3).minus(2) console.log(result)
functiondigitLength(a, b) { varas = a.toString() var bs = b.toString()
var t1 = as.split('.') var t2 = bs.split('.') var len1 = t1[1] ? t1[1].length : 0 var len2 = t2[1] ? t2[1].length : 0
returnMath.pow(10, len1 > len2 ? len1 : len2) }
functionadd(a = 0, b = 0) { var max = digitLength(a, b) return (a * max + b * max) / max } functionminus(a = 0, b = 0) { var max = digitLength(a, b) return (a * max - b * max) / max } functionmultiply(a = 0, b = 0) { var max = digitLength(a, b) return ((a * max) * (b * max)) / (max*max) } functiondevide(a = 0, b = 0) { var max = digitLength(a, b) return (a * max) / (b * max) } add(0.1, 0.2) // 0.3 minus(0.3, 0.2) // 0.1 multiply(0.7, 0.2) // 0.14 devide(0.7, 0.2) // 3.5
7.如何把一个字符串大小写取反,如 Abc => aBC
1 2 3 4 5 6 7 8 9 10
var str = 'aBcDefGhij' functioncapitalReverse1(str) { var arr = str.split('').map(s => s === s.toUpperCase() ? s.toLowerCase() : s.toUpperCase()) return arr.join('') } functioncapitalReverse2(str) { return str.replace(/./ig, (a) => a === a.toUpperCase() ? a.toLowerCase() : a.toUpperCase()) } var newStr = capitalReverse2(str) console.log(newStr)
var S = 'abcdefghijklmnopqrstuvwxyz' var T = 'cdef' functionfindStr(t, s) { try { returnnewRegExp(t).exec(s).index } catch(e) { return -1 } } var index = findStr(T, S) console.log(index) // 2
9、请用闭包定义一个函数,实现每隔1秒,输出从1到500
1 2 3 4 5 6 7 8
functioninterval(num) { let i = 0 const timer = setInterval(function() { if (i >= num) returnclearInterval(timer) console.log(++i) }, 1000) } interval(10)