const removeFromArray = function(firstArray,...toRemove) {
let modifiedArray = [...firstArray];
for (i = 0; i < firstArray.length; i++) {
if (modifiedArray.includes(toRemove[i])) {
modifiedArray.splice(modifiedArray.indexOf(toRemove[i]), 1)
}
}
return modifiedArray;
}这是一个来自odin基础4的项目供参考。当我试图弄清楚如何做的时候,我意外地在不耐烦中找到了解决方案。所述函数的目标是输入一个您喜欢的数组,并通过一个具有两个参数的函数从所述数组中删除您喜欢的任何数组。Ie输入removeFromArray(3, 4,5,3),返回4,5
问题1)为什么在...firstArray问题2)如果我被用来循环你决定为第一个参数(一个数组)输入多少次迭代,为什么它被附加到(toRemovei)?
也许我对这是如何作为一个整体工作的想法是错误的?感谢您的帮助,谢谢!
测试:
const removeFromArray = require('./removeFromArray')
describe('removeFromArray', function() {
it('removes a single value', function() {
expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
});
it('removes multiple values', function() {
expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
});
it('ignores non present values', function() {
expect(removeFromArray([1, 2, 3, 4], 7, "tacos")).toEqual([1, 2, 3, 4]);
});
it('ignores non present values, but still works', function() {
expect(removeFromArray([1, 2, 3, 4], 7, 2)).toEqual([1, 3, 4]);
});
it('can remove all values', function() {
expect(removeFromArray([1, 2, 3, 4], 1, 2, 3, 4)).toEqual([]);
});
it('works with strings', function() {
expect(removeFromArray(["hey", 2, 3, "ho"], "hey", 3)).toEqual([2, "ho"]);
});
it('only removes same type', function() {
expect(removeFromArray([1, 2, 3], "1", 3)).toEqual([1, 2]);
});
});const removeFromArray = function(firstArray,...toRemove) {
let modifiedArray = [...firstArray];
for (let i = 0; i < toRemove.length; i++) {
if (modifiedArray.includes(toRemove[i])) {
modifiedArray.splice(modifiedArray.indexOf(toRemove[i]), 1)
}
}
return modifiedArray;
};
console.log(removeFromArray([3,4,5], 3,5))发布于 2020-07-15 17:07:59
问题1)为什么...firstArray周围的括号是必需的
因为没有它们,它就是一个语法错误。这种形式的展开表示法仅在数组文字中有效。(对象具有相同的表示法,但含义不同。) ...不是运算符,它是仅在特定位置定义的语法(数组文字、对象文字、解构模式、函数参数列表和函数参数列表)。
问题2)如果我被用来循环你决定为第一个参数(一个数组)输入多少次迭代,为什么它被附加到(toRemovei)?
它不应该是,这是不正确的。如果数组的长度超过你想要从数组中删除的元素的数量,那么它就会起作用,因为你要从0到< firstArray.length,所以如果数组中的条目和toRemove中的条目一样多或者更多,你就会看到toRemove的所有条目(如果firstArray更长,还会看到undefined)。
const removeFromArray = function(firstArray, ...toRemove) {
let modifiedArray = [...firstArray];
for (i = 0; i < firstArray.length; i++) {
if (modifiedArray.includes(toRemove[i])) {
modifiedArray.splice(modifiedArray.indexOf(toRemove[i]), 1)
}
}
return modifiedArray;
}
console.log(removeFromArray([1, 2], 3, 4, 1)); // Should be [2], is actually [1, 2]
相反,for循环应该通过< toRemove.length。
这段代码的另一个问题是它从未声明过i,所以它成了我所说的的牺牲品。我建议使用严格模式,使它始终应该是:
"use strict";
const removeFromArray = function(firstArray, ...toRemove) {
let modifiedArray = [...firstArray];
for (i = 0; i < firstArray.length; i++) {
if (modifiedArray.includes(toRemove[i])) {
modifiedArray.splice(modifiedArray.indexOf(toRemove[i]), 1)
}
}
return modifiedArray;
}
console.log(removeFromArray([1, 2], 3, 4, 1)); // Should be [2], is actually [1, 2]
https://stackoverflow.com/questions/62911301
复制相似问题