This log is entirely inspired by reading a log. The original Article is evil eval and new function.
We seldom use the new array method to define arrays. I didn't expect the new array to be so useful. We can create n null elements through the new array (n, at the same time, there are n-1 gaps in the middle of n elements. Through join, we can place some things in the middle of these gaps to form a special string we need, which can not help but inspire me, this feature makes it easy for me to implement a continuous operation of regular elements without repeating ". For example, calculate the sum of values from 1. In the past, we needed to loop from 1 to 100 and then sum up, but we can use this feature of array through a simple lineCodeThe Code is as follows:Copy codeCode: var I = 0, sum = eval ('0' + new array (101). Join ('+ (++ I )'));
In addition, we can perform many similar mathematical operations, such as the following:Copy codeThe Code is as follows: eval ('0' + new array (11). Join ('+ math. Pow (+ + I, 2)') // calculates the sum of squares from 1 to 10.
Eval ('0' + new array (100/2). Join ('+ (I + = 2)') // calculate the sum of 2 + 4 + 6 +... 100
We used to perform these computation in a loop, and now we can use a line of code to handle it, so we have to sigh.Programming LanguageImplicit cleverness, there are always too many things in the programming world to be discovered.
The above JavaScript code is changed to vbs, which is the so-called hardcore solution of vbs exercises:
Copy code The Code is as follows: dim A (101)
Execute (join (a, "s = S + I: I = I + 1 :"))
Msgbox s
Original article: http://demon.tw/programming/no-loop-calculate-1-100-sum.html