【发布时间】:2017-01-30 02:17:16
【问题描述】:
更新
班级提供的 Chai 测试存在问题。无论如何,感谢您的所有帮助!
我正在为一个班级解决一个问题。它要求我们编写一个名为“each”的函数。它应该为集合的每个元素调用迭代器(值,键,集合)。它应该遍历数组,提供对元素、索引和数组本身的访问。它还应该只遍历数组元素,而不是数组的属性(我遇到的另一个问题)。它还接受数组和对象。
在我正在运行的测试中(在底部),它应该返回:
['ant', 'a', animals],
['bat', 'b', animals],
['cat', 'c', animals]
但是,它正在返回:
['ant', '0', Array[3] [0:"ant", 1:"bat", 2:"cat"]]
...数组中的等等。
如何遍历数组以使其返回列表名称,而不是整个数组本身?
var testeach = function(collection, iterator) {
if (Array.isArray(collection)) {
var len = collection.length;
for (var i in collection)
iterator(collection[i], collection.indexOf(collection[i]), collection);
} else {
for (var key in collection)
if (collection.hasOwnProperty(key)) {
iterator(collection[key], key, collection);
}
}
};
var animals = ['ant', 'bat', 'cat'];
var iterationInputs = [];
testeach(animals, function(animal, index, list) {
iterationInputs.push([animal, index, list]);
});
console.log(iterationInputs);
这是使用 Chai 的测试代码。
describe('each', function() {
it('should iterate over arrays, providing access to the element, index, and array itself', function() {
var animals = ['ant', 'bat', 'cat'];
var iterationInputs = [];
_.each(animals, function(animal, index, list) {
iterationInputs.push([animal, index, list]);
});
expect(iterationInputs).to.eql([
['ant', 0, animals],
['bat', 1, animals],
['cat', 2, animals]
]);
});
【问题讨论】:
-
确保您正确阅读和理解问题。也许您错误地解释了所需的输出。 “动物”这个词周围没有引号......
-
谢谢,内特。我直接从单元测试中提取了所需的输出。它肯定想要输入数组的变量名。在示例中,提供了数组 animals。
-
啊,好吧,不是找名字,是看数组里面的数组是不是一样。
-
我的意思是,它不是在寻找字符串“animals”,而是在查看每个数组中的最后一个元素(例如,
['ant', 0, **animals**])是否具有相同的项目(['ant', 'bat', 'cat'])在测试中定义(var animals ...行),它恰好使用与代码中相同的变量名。 -
换句话说,假设 Chai 的
eql方法对数组进行了深度比较,测试应该通过了。
标签: javascript arrays loops