标签:
《JavaScript 框架设计》
版本1:
function repeat(target, n) { return (new Array(n + 1)).join(target) }
版本2:
function repeat(target, n) { return Array.prototype.join.call({length: n + 1}, target) }
版本3:(缓存)
var repeat = (function() { var join = Array.prototype.join, obj = {} return function(target, n) { obj.length = n + 1 return join.call(obj, target) } })();
版本4:(算法)
function repeat(target, n) { var s = target, total = [] while (n > 0) { if (n % 2 == 1) total[total.length] = s if (n == 1) break s += s n = n >> 1 } return total.join(‘‘) }
版本5:
function repeat(target, n) { var s = target, c = s.length * n do { s += s } while (n = n >> 1) s = s.substring(0, c) return s }
版本6:
function repeat(target, n) { var s = target total = ‘‘ while (n > 0) { if (n % 2 == 1) total += s if (n == 1) break s += s n = n >> 1 } return total }
版本7:(递归)
function repeat(target, n) { if (n == 1) { return target } var s = repeat(target, Math.floor(n / 2)) s += s if (n % 2) { s += target } return s }
标签:
原文地址:http://www.cnblogs.com/jzm17173/p/5884516.html