JavaScript中的字符串乘法
原文
I just realized that there is a clever way to implement string multiplication in JavaScript:
String.prototype.times = function(n) {
return Array.prototype.join.call({length:n+1}, this);
};
"js".times(5) // => "jsjsjsjsjs"
This method takes advantage of the behavior of the Array.join() method for arrays that have undefined elements. But it doesn't even bother creating an array with n+1 undefined elements. It fakes it out using and object with a length property and relies on the fact that Array.prototype.join() is defined generically. Because this object isn't an array, we can't invoke join() directly, but have to go through the prototype and use call(). Here's a simpler version that might be just as efficient:
String.prototype.times = function(n) { return (new Array(n+1)).join(this);};
When you call the Array() constructor with a single numeric argument, it just sets the length of the returned array, and doesn't actually create any elements for the array.
I've only tested these in Firefox. I'm assuming that either is more efficient than anything that involves an actual loop, but I haven't run any benchmarks.
解释
String.prototype.times = function(n) {return Array.prototype.join.call({length:n+1}, this);};
"js".times(5) // => "jsjsjsjsjs"
String.prototype.times = function(n) { return (new Array(n+1)).join(this);};
作者简介
我的评论
String.prototype.times = function(n) {if ( n == 1 ) {return this;}
var midRes = this.times(Math.floor(n/2));midRes += midRes;if ( n % 2 ) {midRes += this;}
return midRes;}
评论
发表评论