Hướng dẫn how do you sum up an array in javascript? - làm cách nào để tổng hợp một mảng trong javascript?
TL;DRIf you care about performance, define a function that uses a
BenchmarkI benchmarked a selection of implementations using
In chrome 104, the
Firefox 104 shows similar behaviour:
Thảo luậnImplementations defining an anonymous function are generally slower because creating an anonymous function is a significant overhead. When running the benchmark with a large array, e.g., with length 1000 instead of 100, the difference between Chrome's V8 engine knows how to inline simple anonymous functions in 1 test case. Firefox seems to try something similar but is less efficient in doing so. Non-inlined function calls are pretty slow in js since the call stack is less efficient than the call stack in compiled software.Similar to 3- and 4-based implementations use anonymous functions and are relatively slow. 5 has a specialized 6 implementation, but it is (as of v4.0.0) implemented as a special case of 7, which is relatively inefficient. 8 is the by far slowest test case. This makes sense since constructing the string using concatenations might cause several dynamic allocations (which are slow). Next, the parser has to be invoked and only then can the code be finally executed.I've included some recursive implementations because some people on the internet claim that recursion is faster than loops in js. I can't reproduce their example - using 0 with a loop, both functions take the same time. When calculating the sum, as expected, recursion is much slower than loops, probably due to intense usage of the js call stack.The naive implementation would be manually adding all 100 elements of the array. While being quite inconvenient, this is the fastest implementation. But, luckily, I have no explanation why the 2 loop is slower than the for loop. Iterating the array in reverse doesn't seem to be the problem here.
Có một tổng () trong javascript?Hàm sum () trong d3.js được sử dụng để trả về tổng của các phần tử của mảng đã cho.Nếu mảng trống thì nó sẽ trả về 0. tham số: Hàm này chấp nhận một mảng tham số là một mảng các phần tử có tổng số sẽ được tính toán. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.
Sum += trong JavaScript là gì?Toán tử gán bổ sung ( +=) thêm giá trị của toán hạng bên phải vào một biến và gán kết quả cho biến.Các loại của hai toán hạng xác định hành vi của toán tử gán bổ sung.adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. |