想求数组中对象中的total值最大的对象在数组的下标,怎么写地道点

https://img4.mukewang.com/5c3847fa0001368002570779.jpg

慕码人2483693
浏览 499回答 1
1回答

慕虎7371278

function max(arr, key = 'total') {&nbsp; &nbsp; if (!Array.isArray(arr) && !arr.length) {&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; let index = 0,&nbsp; &nbsp; &nbsp; &nbsp; max = arr[0][key];&nbsp; &nbsp; arr.forEach((item, i) => {&nbsp; &nbsp; &nbsp; &nbsp; let temp = item[key];&nbsp; &nbsp; &nbsp; &nbsp; if (max < temp) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = temp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return index;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript