JSHint不允许我在'for'循环中使用'forEach' [英] JSHint won't let me use 'forEach' in a 'for' loop

查看:128
本文介绍了JSHint不允许我在'for'循环中使用'forEach'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组作为值的对象。

I have an object with arrays as values.

people = {
    'steve':['foo','bar'],
    'joe':['baz','boo']
}

对于每个键,我想循环相应数组中的值。足够简单:

For each key, I would like to loop over the values in the corresponding array. Simple enough:

for ( var person in people ) {
    person.forEach( function(item) {
      console.log(item)
    })
}

但JSHint抱怨:

Don't make functions within a loop.

这是否真的是我的代码问题?我非常喜欢简短的ES5 for循环语法。我是否需要使用ES3样式或以其他方式更改我的代码?

Is this truly an issue with my code? I quite like the short ES5 for loop syntax. Do I need to use the ES3 style or change my code in some other way?

推荐答案

那里有两个问题,一个那个JSHint正在警告你,而且是一个更基础的。

There are two issues there, the one that JSHint is warning you about, and a more fundamental one.

JSHint警告你的是理论上,每次该循环运行,创建一个新函数。这样会更好:

The thing that JSHint is warning you about is that in theory, every time that loop runs, a new function is created. This would be better:

for ( var person in people ) {
    person.forEach(handlePerson);
}
function handlePerson(item) {
  console.log(item)
}

我说理论上因为虽然规范要求每次都创建一个新函数 object ,但这并不意味着引擎不能重用底层函数的实现,并不意味着如果您没有为其分配任何其他属性或保留对它的引用,则引擎不能重用相同的函数对象。我向V8人询问过它(V8是Chrome中的JavaScript引擎),他们说Chrome会...在大多数情况下......为在源代码中的同一点创建的不同函数对象重用底层函数实现,并且他们会期望大多数其他引擎都会这样做。

I say "in theory" because although the spec requires that a new function object be created each time, that doesn't mean engines can't reuse the underlying implementation of the function, and it doesn't mean that engines can't reuse the same function object if you didn't assign any other properties to it or keep a reference to it. I asked the V8 guys about it (V8 being the JavaScript engine in Chrome), and they said that Chrome will "...in most cases..." reuse the underlying function implementation for different function objects created at the same point in the source code, and that they would "expect" that most other engines would do the same.

因此,在这种特殊情况下,JSHint可能会有点过分。但它经常是一个有用的警告,特别是如果你在循环中创建的函数引用了循环期间内容发生变化的变量,这是人们经常出现的闭包错误。

So JSHint may be being a bit over-the-top in this particular case. But it's frequently a useful warning, particularly if the functions you're creating inside the loop refer to variables whose contents change during the loop, which is the classic closure error people make.

但更重要的是, person String (它是中属性的名称>人)和字符串没有 forEach 。你想要:

But more fundamentally, person is a String (it's the name of a property in people), and String doesn't have forEach. You wanted:

for ( var person in people ) {
    people[person].forEach(handlePerson);
}
function handlePerson(item) {
  console.log(item)
}

...例如,人[人] 获取该密钥的数组。

...e.g., people[person] to get the array for that key.

这篇关于JSHint不允许我在'for'循环中使用'forEach'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆