![](/img/trans.png)
[英]Why does this not return an array containing all but the last element of of an array located at a given key
[英]return the smallest element in the array located in the given key
我想返回給定對象和鍵中的最小元素,但是如果給定數組為空或給定鍵處的屬性不是數組,則它應該返回undefined。 我解決了,但是我對自己的方法並不完全滿意。 有什么建議可以縮短我的代碼?
let obj = {
key: [8, 5, 10, 15, 11, 21, 1, 25]
};
const smallest = (obj, key) => {
return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined : obj[key].reduce((l, s) => l < s ? l : s)
}
smallest(obj, 'key');
您可以進行檢查並返回最小值。
const smallest = (obj, key) => Array.isArray(obj[key]) && obj[key].length ? Math.min(...obj[key]) : undefined; console.log(smallest({ key: [8, 5, 10, 15, 11, 21, 1, 25] }, 'key')); console.log(smallest({ key: [8] }, 'key')); console.log(smallest({ key: [] }, 'key')); console.log(smallest({}, 'key'));
可以使用Math.min()
而不是reduce來在數組上使用spread operator(...)
let obj = { key: [8, 5, 10, 15, 11, 21, 1, 25] }; const smallest = (obj, key) => { return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined : Math.min(...obj[key]); } console.log(smallest(obj, 'key'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.