JavaScript中Array子类如何正确使用.splice方法?
关于JavaScript Array子类的实现与优化
嘿,我看了你写的CustomArray子类代码,思路完全在线!这个实现已经能满足用数组初始化、添加移除元素的需求了,不过咱们可以再微调下,让它更灵活,同时确认它的工作逻辑符合预期。
先说说你原代码的优点:
- 正确继承了
Array,所以你的CustomArray实例能直接使用所有原生数组方法(比如map、filter) - 构造函数里用
super(...array)展开传入的数组元素,能正确初始化实例内容 remove方法的逻辑清晰:找到元素索引后用splice移除,没找到就返回空数组,完全合理
优化后的代码(更灵活的初始化)
我稍微调整了构造函数,让它既支持传入单个数组参数,也支持直接传入多个元素,适配更多场景:
class CustomArray extends Array { constructor(...args) { // 处理两种初始化场景:传入单个数组 或 传入多个元素 if (args.length === 1 && Array.isArray(args[0])) { super(...args[0]); } else { super(...args); } console.log('Initiated array:', this); } remove(element) { const index = this.indexOf(element); if (index !== -1) { // splice返回被移除的元素组成的数组,直接返回即可 return this.splice(index, 1); } // 未找到匹配元素时返回空数组 return []; } }
测试示例
来看看实际使用效果:
// 用已有数组初始化 const a = ['a', 'b', 'c', 'd', 'e']; const list = new CustomArray(a); console.log(list); // 输出: CustomArray(5) ["a", "b", "c", "d", "e"] // 移除存在的元素 list.remove('c'); console.log(list); // 输出: CustomArray(4) ["a", "b", "d", "e"] // 移除不存在的元素 const removed = list.remove('x'); console.log(removed); // 输出: [] // 直接传入多个元素初始化 const anotherList = new CustomArray('f', 'g', 'h'); console.log(anotherList); // 输出: CustomArray(3) ["f", "g", "h"]
额外扩展:移除所有匹配元素
如果需要移除数组中所有匹配的元素(而不只是第一个),可以给CustomArray加个removeAll方法:
removeAll(element) { const removedElements = []; let index; // 循环查找并移除,直到找不到匹配元素 while ((index = this.indexOf(element)) !== -1) { removedElements.push(...this.splice(index, 1)); } return removedElements; } // 使用示例 const duplicateList = new CustomArray('a', 'b', 'a', 'c', 'a'); const removedAll = duplicateList.removeAll('a'); console.log(removedAll); // 输出: ["a", "a", "a"] console.log(duplicateList); // 输出: CustomArray(2) ["b", "c"]
需要注意的是,因为继承了Array,CustomArray的实例本质上还是原生数组,所以所有数组的原生特性(比如自动维护length属性)都能正常工作,这也是ES6类继承原生构造函数的便利之处。
内容的提问来源于stack exchange,提问作者ands
相关产品推荐
相关产品推荐

