简体   繁体   English

array.forEach的怪异行为

[英]Weird behaviour with array.forEach

I have an array of objects: 我有一个对象数组:

var conversions = [
    { regex: ..., names: [ ... ] },
    ...
];

I loop through each conversion object and pass them to a certain function: 我遍历每个转换对象,并将它们传递给某个函数:

conversions.forEach(function(conv) {
    // function selection logic

    var result = func(message, conv); // func is the selected function, message is defined before

    // result logic
}

The loop works fine for all the objects in the array, but after the last object, a weird object is passed to the callback which is not part of my array. 循环对于数组中的所有对象都可以正常工作,但是在最后一个对象之后,一个奇怪的对象将传递给回调函数,该回调函数不属于我的数组。 Adding console.log(conv); 添加console.log(conv); at the very beginning of the callback prints out all the conversions correctly, but the last weird object is printed out as epäluku undefined . 在回调的最开始就正确地打印了所有转换,但是最后一个奇怪的对象被打印为epäluku undefined "Epäluku" is a bad Finnish translation for NaN , which means the output is the same as NaN.toLocaleString() + " " + undefined . “Epäluku”是NaN的不好的芬兰语翻译,这意味着输出与NaN.toLocaleString() + " " + undefined

I haven't been able to figure out why this odd object is there, or how to filter it. 我还不能弄清楚为什么有这个奇怪的对象,或如何过滤它。 I've tried checking it against null and undefined but neither did the trick. 我试过针对nullundefined检查,但是技巧都没有。 I've even tried checking it against NaN.toLocaleString() + " " + undefined but that didn't work either. 我什至尝试过根据NaN.toLocaleString() + " " + undefined检查它,但是那也不起作用。

This is part of a userscript, running in Chrome using Tampermonkey. 这是用户脚本的一部分,使用Tampermonkey在Chrome中运行。

Turns out the issue was my code all along. 原来问题一直是我的代码。 In an unrelated function I was adding elements to the conversions array rather than the correct array within that function. 在一个不相关的函数中,我在向conversions数组添加了元素,而不是在该函数中添加了正确的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM