如果数组按升序排序,则返回 1
;如果按降序排列则返回-1
;如果未排序则返回0
。
计算前两个元素的排序方向 direction
。
使用 Object.entries()
来循环使用数组对象并对它们进行比较。
如果 direction
改变,则返回 0
,如果直到最后一个元素, direction
没有改变,则返回 direction
。
const isSorted = arr => { const direction = arr[0] > arr[1] ? -1 : 1; for (let [i, val] of arr.entries()) if (i === arr.length - 1) return direction; else if ((val - arr[i + 1]) * direction > 0) return 0; };
isSorted([0, 1, 2, 3]); // 1 isSorted([0, 1, 2, 2]); // 1 isSorted([4, 3, 2]); // -1 isSorted([4, 3, 5]); // 0
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂