Discuss / JavaScript / 练习

练习

Topic source

凌翊CJV

#1 Created at ... [Delete] [Delete and Lock User]

arr.sort((x, y) => { return x - y; }); console.log(arr); // [1, 2, 10, 20]

return的是一个表达式的话,return都不需要好吧

直接 arr.sort((x, y) => x-y);

不写return结果是10,20,1,2

arr.sort((x, y) => {x-y});加了{}结果是10,20,1,2

槲寄君

#5 Created at ... [Delete] [Delete and Lock User]

楼上的你是没有运行过呢还是写错了,不加return是可以的

桀呐

#6 Created at ... [Delete] [Delete and Lock User]

因为外层有{...} 所以直接写 x-y 就相当于直接执行这一句而不是返回,返回值是undefined,所以无法进行排序。 不写return的写法是要把外层的{...}删掉,arr.sort((x, y) => x - y);这样函数体才是相当于{return x - y}

青涯白漉

#7 Created at ... [Delete] [Delete and Lock User]

我加了return之后才正确的。。。


  • 1

Reply