Js calculates the sum of all numbers in the array

Source: Internet
Author: User

Today, I encountered a problem of calculating the array summation. I always felt that the for loop summation was troublesome. I searched for the problem and thought that this method was good, but the eval here didn't know whether it was good or not.

Join Function

The Code is as follows: Copy code

Var arr = [1, 2, 3, 4, 5, 6];

Var value = eval (arr. join ("+ "));

Of course, we can also use the Traversal method.

Example

The Code is as follows: Copy code

<Title> calculate the sum of all numbers in the array </title>
<Style>
Body {color: #999; font: 12px/1.5 Tahoma ;}
# Outer {width: 500px; margin: 0 auto ;}
# Outer input {padding: 3px; border: 1px solid # ccc; font-family: inherit; width: 220px; margin-right: 10px ;}
. Sum {font-size: 30px; color: red ;}
</Style>
<Script>
Window. onload = function ()
{
Var oBtn = document. getElementsByTagName ("button") [0];
Var oInput = document. getElementsByTagName ("input") [0]
Var oStrong = document. getElementsByTagName ("strong") [0];
OInput. onkeyup = function ()
{
This. value = this. value. replace (/[^ (d) | (,)]/, "")
}
OBtn. onclick = function ()
{
Var sum = 0;
Var oInput = document. getElementsByTagName ("input") [0]. value. split (",");
For (var I in oInput)
{
Sum + = parseInt (oInput [I])
}
OStrong. innerHTML = sum
}
}
</Script>
</Head>
<Body>
<Div id = "outer">
<Label> <input type = "text" value = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15"/> <span> enter the sum of numbers, numbers are separated by commas (,). </span> </label>
<P> <button> sum </button> </p>
<Strong class = "sum"> </strong>
</Div>

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.