【发布时间】:2022-12-26 09:42:44
【问题描述】:
这是 odin 项目的第四个项目,所有测试都通过了,但是第五个需要删除所有元素的测试失败了,当我运行代码时,它返回一个数组,其中包含原始数组中一半的元素,然后再进行变异。
我不知道为什么在第五次测试中它不返回空数组。
const removeFromArray = function (array, ...deleteElement) {
for (let i = 0; i < array.length; i++) {
if (array.includes(deleteElement[i])) {
array.splice(array.indexOf(deleteElement[i]), 1);
}
}
return array;
};
const randomArray = [1, 2, 3, 4];
console.log(removeFromArray(randomArray, 1, 2, 3, 4));
这是测试
const removeFromArray = require('./removeFromArray')
describe('removeFromArray', () => {
test('removes a single value', () => {
expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
});
test('removes multiple values', () => {
expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
});
test('ignores non present values', () => {
expect(removeFromArray([1, 2, 3, 4], 7, "tacos")).toEqual([1, 2, 3, 4]);
});
test('ignores non present values, but still works', () => {
expect(removeFromArray([1, 2, 3, 4], 7, 2)).toEqual([1, 3, 4]);
});
test.skip('can remove all values', () => {
expect(removeFromArray([1, 2, 3, 4], 1, 2, 3, 4)).toEqual([]);
});
test.skip('works with strings', () => {
expect(removeFromArray(["hey", 2, 3, "ho"], "hey", 3)).toEqual([2, "ho"]);
});
test.skip('only removes same type', () => {
expect(removeFromArray([1, 2, 3], "1", 3)).toEqual([1, 2]);
});
});
【问题讨论】:
-
关于你之前的问题,现在已经被删除了,我只想说,编程中总有一些概念,你刚开始学的时候,对你来说没有任何意义,看起来不清楚,但是当你继续学习的时候,就知道了。更多最重要的是做一些项目,在某些时刻,砰!你会意识到这是为了什么,我们打算使用构造函数的目的是什么,等等,所以这里重要的是进行搜索,但如果你注意到了一般的想法,现在就可以了,不要再想太多了它,继续前进!你会意识到,这只是需要一些时间 :)
标签: javascript arrays splice