【发布时间】:2022-01-03 00:37:36
【问题描述】:
我编写了一个程序来比较数组并像在 Lodash 中一样在没有方法的情况下实现。除了我编写的使用 assertEqual 函数测试我的结果的测试之外,一切都运行良好,我不知道为什么测试失败了。
const assertEqual = function (actual, expected) {
if (actual === expected) {
console.log(`✅✅✅ Assertion Passed: ${actual} === ${expected}`);
} else {
console.log(`???????????? Assertion Failed: ${actual} !== ${expected}`);
}
return;
};
const eqArrays = function (arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
assertEqual(eqArrays([1, 2, 3], [1, 2, 3]), true);
const without = function (source, itemsToRemove) {
let newArray = [];
for (let i = 0; i < source.length; i++) {
if (!itemsToRemove.includes(source[i])) {
newArray.push(source[i]);
}
}
return newArray;
}
console.log(without([1, 2, 3], [1]));
console.log(without(['1', '2', '3'], [1, 2, '3']));
assertEqual(without([1, 2, 3], [1]), [2, 3]);
【问题讨论】:
-
我没有看到任何 lodash 代码。
-
您的
assertEqual调用结束不使用eqArrays- 非原始值通过 reference、[2, 3] === [2, 3]进行比较是false。如果传递数组,我会将该代码更改为具有assertEqual使用eqArrays,否则你会得到无用的Assertion Failed: false !== true。 -
我认为这只是一个错字。
assertEqual(without([1, 2, 3], [1]), [2, 3]);应该是assertEqual(eqArrays(without([1, 2, 3], [1]), [2, 3]), true);(就像您通过的第一个测试一样)。 -
顺便提一下:您添加了代码,它有效,并且与问题完全无关(整个
eqArrays的东西,以后再也没有使用过),但它添加了一个我错过的滚动条,并且我阅读了“测试”,看到了一项测试,该测试有效。你差点在那儿无缘无故地开枪打死自己? -
哦!我的错。它现在适用于
assertEqual(eqArrays(without([1, 2, 3], [1]), [2, 3]), true);
标签: javascript node.js testing lodash assertion