Codesandbox中findLast与findLastIndex方法不存在问题求助
问题原因
findLast 和 findLastIndex 是ES2022(ES13)新增的数组方法,Codesandbox默认的项目配置可能没启用对该版本ECMAScript的支持,导致运行时识别不了这些方法。
解决方案
- 检查Babel转译配置:
要是项目用了Babel,得先装@babel/plugin-proposal-array-find-from-last插件,然后在Babel配置文件(比如.babelrc或者babel.config.json)里启用它:{ "plugins": ["@babel/plugin-proposal-array-find-from-last"] } - 调整Codesandbox环境设置:
在Codesandbox项目里,打开左侧面板的「Settings」→「JavaScript Settings」,把「ECMAScript Version」改成「ES2022」或更高版本。 - 手动添加兼容代码(备选):
要是上面的方法不管用,可以手动加polyfill来兼容旧环境:// 给Array添加findLastIndex的兼容实现 if (!Array.prototype.findLastIndex) { Array.prototype.findLastIndex = function(predicate) { for (let i = this.length - 1; i >= 0; i--) { if (predicate(this[i], i, this)) { return i; } } return -1; }; } // 给Array添加findLast的兼容实现 if (!Array.prototype.findLast) { Array.prototype.findLast = function(predicate) { for (let i = this.length - 1; i >= 0; i--) { if (predicate(this[i], i, this)) { return this[i]; } } return undefined; }; }
内容的提问来源于stack exchange,提问作者The Truth
相关产品推荐
相关产品推荐

