gpt4 book ai didi

javascript - 查找日期晚于当前日期的对象

转载 作者:行者123 更新时间:2023-11-28 17:00:35 27 4
gpt4 key购买 nike

items 数组中,它查找日期晚于当前日期 new Date () 的对象。 let findObject = this.state.items.find(date => new Date(date.date)> new Date()); 我在页面上显示找到的日期。问题:let findObject = this.state.items.find (date => new Date (date.date)> new Date ()); 只找到一个对象,应该找到更多对象。

此处代码:https://stackblitz.com/edit/react-fm2g6y

class Item extends Component {

render() {
console.log(this.props.findObject);

return (
<li>
<div>
{moment(this.props.findObject.date).format("YYYY-MM-DD")}
</div>
</li>
)
}
}


class App extends React.Component {
constructor() {
super();

this.state = {

items: [
{
id: 1,
date: 'Sun Oct 01 2017 05:30:00 GMT+0530 (IST)'
},
{
id: 2,
date: 'Fri Aug 23 2019 05:30:00 GMT+0530 (IST)'
},
{
id: 3,
date: 'Wed Oct 23 2019 04:30:00 GMT+0530 (IST)'
},
{
id: 4,
date: 'Wed Oct 24 2019 05:30:00 GMT+0530 (IST)'
},
{
id: 5,
date: 'Thu Oct 05 2019 05:30:00 GMT+0530 (IST)'
}]
};
}


render() {
let findObject = this.state.items.find(date => new Date (date.date) > new Date());

return (
<div>
<ul>
{
this.state.items
.map((item, index) =>
<Item
key={index}
index={index}
item={item}
findObject = {findObject}
/>
)
}
</ul>
</div>
);
}
}

最佳答案

如果您需要多个结果,请将 this.state.items.find 替换为 this.state.items.filter

The find() method returns the value of the first element in the array that satisfies the provided testing function

这意味着它只返回与其匹配的第一个内容。

(引用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)

另一方面

The filter() method creates a new array with all elements that pass the test implemented by the provided function

意味着它将返回与其匹配的多个内容

(引用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

关于javascript - 查找日期晚于当前日期的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57623588/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com