`.toSorted()`仅在浏览器中可用。

huangapple go评论68阅读模式
英文:

.toSorted() works only in a browser

问题

sortedHeights = heights.sort();
英文:

I am working on a LeetCode problem, I want to assign a variable to a sorted copy of an array.

sortedHeights = heights.toSorted()

However, this returns the following error heights.toSorted is not a function.
I looked up the issue on MDN, and found the following code snippet:

const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

I try to run this code snippet as well on WebStorm and I get the same error, however, when I run it in a browser it works. Why is that?

答案1

得分: 9

.toSorted() 是一个新方法。正如你在链接的 MDN 文档中所看到的,它在 node.js 中尚不受支持。

英文:

.toSorted() is a new method. As you can see in the MDN doc you linked, it's not supported in node.js yet.

答案2

得分: 7

Array.prototype.toSorted() 在 Node.js 版本 20+ 中受支持。大多数开发者使用 Node.js 的 LTS 版本(目前是版本 18)。所以,如果你在 WebStorm 中使用 Node.js 版本 19、18 或更低版本,.toSorted() 不受支持。

至于 LeetCode,我看到它目前使用 Node.js 16 运行你的代码。因此,你可以在这段时间内使用这个替代代码(与.toSorted() 有效等效):

sortedHeights = [...heights].sort()

还请注意,.toSorted() 目前在最新版本的 Chrome 和 Edge(从版本 110 开始)、Safari(从版本 16 开始)、Firefox(从版本 115 开始)以及一些其他浏览器中受支持,但在较旧版本中不受支持 - 以防你假设它在所有浏览器中都有效。

请查看 Array.prototype.toSorted() MDN 浏览器兼容性部分 获取最新的支持详情。

英文:

At the time of this answer, Array.prototype.toSorted() is supported by Node.js version 20+. Most developers use the Node.js LTS version (currently version 18). So if you're using Node.js version 19, 18 or lower in WebStorm, .toSorted() is not supported.

For the case of LeetCode, I see that it currently uses Node.js 16 to run your code. So you might want to resort to this alternative (and effectively equivalent) code for the time being:

sortedHeights = [...heights].sort()

Also note that .toSorted() is currently supported in recent versions Chrome and Edge (from version 110), Safari (from version 16), Firefox (from version 115) and some other browsers, it's not supported in older versions - just in case you made an assumption that it works in all browsers.

Check the Array.prototype.toSorted() MDN browser compatibility section for latest support details.

huangapple
  • 本文由 发表于 2023年4月13日 22:05:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定