A case study of JavaScript recursive operation _javascript Skills

Source: Internet
Author: User

This article analyzes the JavaScript recursive operation. Share to everyone for your reference, specific as follows:

Problem

A simple recursion that asks for the factorial of N:

function factorial (n) {
  if (n<=1)
  {return
    1;
  } else{return
    factorial (n-1) *n;
  }


If you use it as follows, you will get an error:

var fcopy = factorial;
factorial = null;
Alert (Fcopy (3));

Because the fcopy point to the function entity called factorial, factorial has been freed.

Way to solve

Using Arguments.callee

When the stream enters the function, it creates the runtime environment (scope chain, etc.) of the function, including arguments, where the arguments object has a property pointing to the function itself: Arguments.callee.

function factorial (n) {
  if (n<=1)
  {return
    1;
  } else{return
    Arguments.callee (n-1) *n;
  }


However, callee is not available in strict mode.

Using function expressions

var factorial = (function f (n) {
  if (n<=1)
  {return
    1;
  } else{return
    F (n-1) *n
  }
)

This is not what new technology is used, but in the original concept of an application, in the definition of factorial, directly create a function, and then the function of the reference to assign value to factorial.

More readers interested in JavaScript-related content can view this site: "JavaScript traversal algorithm and tips summary", "javascript array operation skills Summary", "JavaScript Mathematical calculation Usage Summary", " JavaScript data structure and algorithm skills summary, "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and techniques summary" and "JavaScript error and debugging skills Summary"

I hope this article will help you with JavaScript programming.

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.