const App = () => {
const course = [{
id: 1,
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
我正在嘗試計算每門課程中練習的總和,這樣我就可以在每門課程結束時得到一些東西,上面寫著 Total exercise: 31 at the end of Half Stack Application Development and total exercise 10: at the end of Node .js
我試過了
const totals = course.map(c => c.parts.map(c => c.exercises.map(c => c.reduce((a, b) => a b, 0))))
但收到的 c.exercises.map 不是函式。
我如何計算每個 c.exercises 的總和?
練習在控制臺中看起來像這樣:
(2) [Array(3), Array(2)]
0: (3) [10, 7, 14]
1: (2) [3, 7]
length: 2
uj5u.com熱心網友回復:
這僅計算每門課程的練習次數
const calculateTotalExercises = course =>
course.map(c => c.parts.reduce((res, {
exercises
}) => res exercises, 0))
const course = [{
id: 1,
name: 'Half Stack application development',
parts: [{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
console.log(calculateTotalExercises(course))
像這樣將練習的總數添加到陣列中可能會更方便
const calculateTotalExercises = course =>
course.map(c => ({...c, totalExercise : c.parts.reduce((res, p) => res p.exercises, 0)}))
const course = [{
id: 1,
name: 'Half Stack application development',
parts: [{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
console.log(calculateTotalExercises(course))
uj5u.com熱心網友回復:
你可以從分解問題開始。這是我解決這個問題的方法。
我創建了一個函式來查找一門課程的練習總數
let totalExerciseForOneCourse = (parts) => {
return parts.reduce((prev, curr) => prev curr.exercises, 0)
}
然后我們使用 map 方法遍歷課程陣列中的每個課程,回傳一個新的物件陣列,其中包含課程陣列中的所有內容,并添加一個totalExercises物件屬性
let newCourses = courses.map((course) => {
const total = totalExerciseForOneCourse(course.parts);
return Object.assign({}, course, {
totalExercises: total
})
})
我們的totalExerciseForOneCourse函式接受一個陣列引數,并使用 array.reduce 方法計算一門課程的所有練習的總和
newCourses包含我們的新陣列,其中包含所有以前的和新的資訊
JSFiddle -
https://jsfiddle.net/swish933/9fwzysxa/
uj5u.com熱心網友回復:
你可以做
let total = 0
courses.map(course => course.parts.map(part => total = part.exercises)
編輯: 以防萬一您需要使用reduce:
const total = courses.map(course => course.parts.reduce(e1,e2 => e1 e2 ))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466636.html
標籤:javascript 数组 反应
上一篇:將地圖項插入DynamoDb
下一篇:從后端取回資料后如何加載檔案二
