forEach 在未定义数组处失败

forEach failure at undefined array

很长一段时间我都用

for (var n in nodes) {f(nodes[n])} 

相当成功。但是,切换到整洁

nodes.forEach(f)

我注意到它在未定义的节点处失败,whareas for-in 循环没有。我想知道,我怎样才能使 forEach 以相同的方式运行?

您将首先使用 for(;;) 循环 测试是否存在 undefined

您不应该使用 for ( in ) 来迭代类似数组的对象。您应该使用 for(;;) 循环或使用以对象作为上下文的标准数组循环函数(例如 Array.protoype.forEach.call(arrayLikeObject, fn).

嗯,你不能。因为.forEach只是一个函数,你不能在null/undefined上调用函数。你可以做的是:

(arr || []).forEach(f);

但对于这些情况,我建议使用 for of 循环或常规 for 循环,它们与 .forEach 相同。 for in 具有不同的语义。

添加 if (typeof nodes !== 'undefined')

会更干净

我建议先用 Array.isArray

检查一下
Array.isArray(nodes) && nodes.forEach(cb);