编写一个名为“getLengthOfShortestElement”的函数。
给定一个数组,“getLengthOfShortestElement”返回给定数组中最短字符串的长度。
注释: * 如果数组为空则返回0。
我的代码:
function getLengthOfShortestElement(arr) {
if (arr.length === 0) return 0;
return arr.sort(function(a, b){
return a.length> b.length;
}).unshift();
}
getLengthOfShortestElement(['one', 'two', 'three']); // 3
为什么它没有通过应该通过仅返回最短元素的第一个实例来“处理关系”的测试。另外,有没有更好的方法让空数组返回0?
最佳答案
这可以通过 reducer 来完成。
function getLengthOfShortestElement(arr) {
if (!arr.length) return 0;
return arr.reduce(function(prev, current) {
if (prev === null) return current.length;
if (current.length < prev) return current.length;
return prev;
}, null);
}
关于javascript - 找到数组中最短元素的第一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274690/