String multiplication in JavaScript

Source: Internet
Author: User

In Ruby, the "*" operator used with a string on the left and a number on the right does string repetition. "Ruby" * 2 evaluates to "RubyRuby", for example. this is only occasionally useful (when creating lines of hyphens for ASCII tables, for example) but it seems kind of neat. and it sure beats having to write a loop and concatenate n copies of a string one at a time -- that just seems really inefficient.

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.

Explanation
My English is so bad that I can't translate it word by word. I can only explain what it means.

In Ruby, the "*" operator uses a string as the left parameter and a number as the right parameter to implement string duplication. For example, the value of "Ruby" * 2 is "RubyRuby ". This is useful only in a few places (for example, generating a table consisting of ASCII characters such as hyphens), but it is very concise. It is much less efficient than writing a loop to connect strings for n times.

I just found that there is a clever technique in JavaScript to implement string multiplication:

For more information about the code, see the original article.
This method calls an Array. join () action of an Array whose elements are all "undefined. However, it does not actually create an array containing n + 1 "undefined" elements. It uses an anonymous object that contains the length attribute and relies on the original function join () of the Array object (). Because "Object" is not an array and cannot directly call join (), it must be implemented through the call () of the prototype. A simple version with the same effect is provided below:

For more information about the code, see the original article.
When we call the constructor with a parameter of Array, we only set the length of the Array. In fact, no elements of the Array are created.

I only tested it in Firefox. I guess it will be more effective than a normal loop, But I didn't perform a benchmark test.

Author Profile
David Flanagan is a computer programmer fascinated by Java writing. He spent most of his time writing Java-related books. David earned a computer science degree in engineering at the Massachusetts Institute of Technology. He lives on the Pacific Northwest Coast between Seattle and Vancouver. He published best-selling books in o'reilly, including Java in a Nutshell, Java Foundation Classes in a Nutshell, Java Enterprise in a Nutshell, and JavaScript: the Definitive Guide, JavaScript Pocket Reference, and The Ruby Programming Language.

My comments
If efficiency is to be considered, it may be more efficient to slightly optimize loop iterations. For example, in the following recursive call, the algorithm complexity is O (log2n ). In Google Chrome, the test result is faster than that of David, but I have to admit that his method is elegant!

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;
}

Postscript
David adopted my suggestion and wrote a non-recursive version for us. See his blog article: http://www.davidflanagan.com/2009/08/good-algorithms.html.

Source: http://blog.csdn.net/redraiment/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.