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