mza*_*ars 7 javascript arrays sum ecmascript-6 reactjs
我有这个数组
const data = [
{"One",prix:100},
{"Two",prix:200},
{"Three",prix:300}
]
Run Code Online (Sandbox Code Playgroud)
我想得到所有这些的总和,prix如下所示:
sum = 600
Run Code Online (Sandbox Code Playgroud)
Viv*_*shi 14
您可以使用reduce:
data.reduce((a,v) => a = a + v.prix , 0 )
Run Code Online (Sandbox Code Playgroud)
data.reduce((a,v) => a = a + v.prix , 0 )
Run Code Online (Sandbox Code Playgroud)
reduce() 方法对数组的每个元素执行(您提供的)reducer 函数,从而产生单个输出值。
arr.reduce(callback, initialValue);
Run Code Online (Sandbox Code Playgroud)
reducer 只会返回一个值,并且仅返回一个值,因此得名“reduce”。回调是为数组中的每个元素运行的函数。
和函数参数函数(总计,当前值,索引,arr):
Argument Description
total Required.The initialValue, or the previously returned value of the function
currentValue Required.The value of the current element
currentIndex Optional.The array index of the current element
arr Optional.The array object the current element belongs to
Run Code Online (Sandbox Code Playgroud)
在此示例中使用以下代码:
arr.reduce(callback, initialValue);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39536 次 |
| 最近记录: |