在以下示例代碼中,如何在日期中找到任何 2021 年陣列的所有索引?感謝您的任何指導!
function test() {
const dates = [
'October 31, 2020',
'November 30, 2020',
'December 31, 2020',
'January 31, 2021',
'February 28, 2021',
'March 31, 2021',
];
// How should the following code be changed to get indexes of any array of year 2021, which should be 3,4,5?
// The following code returned only the first array index, 3, not 3,4,5.
var indexes = dates.findIndex(el => el.includes('2021'));
console.log(indexes);
}
uj5u.com熱心網友回復:
使用減少:
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function test() {
const dates = [
'October 31, 2020',
'November 30, 2020',
'December 31, 2020',
'January 31, 2021',
'February 28, 2021',
'March 31, 2021',
];
// The following code returned 3,4,5.
var indexes = dates.reduce((acc,el,i) => el.includes('2021') ? [...acc,i] : acc,[]);
console.log(indexes);
}
test()
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340795.html
下一篇:如何將兩個陣列合二為一?
