javascript - 查找数组的第一个元素并将其显示在 map 函数中但有警告 - React
问题描述
我有这样的数据:
{
"title": 0,
"name": 0,
"score": 0,
"summary": [
{
"id": 1,
"start": "2019-11-01",
"end": "2019-11-04"
},
{
"id": 2,
"start": "2019-11-01",
"end": "2019-11-04"
}
]
}
我正在尝试访问摘要的第一个元素,所以我尝试了这个:
const newDate = new Date(data?.summary.map((d: any, index: number) => {
if (index === 0) {
return (
new Date(d.start)
)
}
})),
虽然它正在工作,但我收到警告:
Array.prototype.map() 期望在箭头函数 array-callback-return 的末尾返回一个值
我知道这一定是因为我没有在回调中返回任何内容并且返回在 if 语句中?
解决方案
if (index === 0) {
return (
new Date(d.start)
)
如果 index === 0,您只会返回一个值。
我不确定您要实现什么目标:
const newDate = new Date(data?.summary.map((d: any, index: number) => {
if (index === 0) {
return (
new Date(d.start)
)
}
})),
我想:
const newDate = newDate(data?.summary[0]?.start)
会做的事。
推荐阅读
- java - 如何在 JShell 中加载外部文件?
- excel - Excel - 如何在 Excel 中将包含货币的单行拆分为多行?
- pdf - 使用 Google Apps 脚本从 Google 表格导出 PDF 时的 setName
- autohotkey - 在像素更改时关闭 AHK 脚本需要帮助
- nestjs - 'TypeError:无法解构'notifsDto'的属性'title',因为它未定义'
- php - /pusher/auth 端点在 Laravel 中返回 404
- php - 如何在PHP中按字符将数组拆分为关联数组
- django-views - 如何 - 在 django 中将字符串呈现为模板
- javascript - Node.JS MySQL 将结果记录到控制台而不被要求和奇怪的行为
- python - 寻找 R 的 rpart 函数的 Python 等效项