实现Array.prototype.at()方法遇异常:返回值不符预期求排查
自定义Array.at()方法返回结果错误的排查与修复
问题场景
Array.prototype.at()是ES2022新增特性,接收数组元素索引并返回对应元素。自定义实现该方法时,调用arr.myAt(1)预期返回'HTML',但实际始终返回'JavaScript'。
正确用法示例
const arr = ["JavaScript", "HTML", "ES2022", "CSS", "Chrome", "W3"]; console.log(arr[1]) // 输出: HTML // 等同于 console.log(arr.at(1)) // 输出: HTML
错误实现代码
const arr = ["JavaScript", "HTML", "ES2022", "CSS", "Chrome", "W3"]; Array.prototype.myAt = function (index) { for (let index = 0; index < this.length; index++) { return this[index]; } }; let res = arr.myAt(1); console.log(res); // 输出: JavaScript
错误原因分析
- 参数被覆盖:函数内部的
for循环声明了let index = 0,直接覆盖掉传入的index参数,导致外部传入的索引值完全失效。 - 循环提前终止:循环的第一次迭代就执行
return this[index],此时index为0,直接返回数组第一个元素,循环没有机会执行到后续逻辑。
正确实现方式
要完全还原at()的功能,需要同时支持正索引和负索引(负索引表示从数组末尾倒序计数,比如-1对应最后一个元素):
const arr = ["JavaScript", "HTML", "ES2022", "CSS", "Chrome", "W3"]; Array.prototype.myAt = function (index) { // 处理负索引:将负索引转换为合法的正索引 const realIndex = index < 0 ? this.length + index : index; // 索引越界时返回undefined,和原生at()行为保持一致 if (realIndex < 0 || realIndex >= this.length) { return undefined; } return this[realIndex]; }; // 测试用例 console.log(arr.myAt(1)); // 输出: HTML console.log(arr.myAt(-1)); // 输出: W3 console.log(arr.myAt(10)); // 输出: undefined
内容的提问来源于stack exchange,提问作者newcoder
相关产品推荐
相关产品推荐

