简体   繁体   English

Scope 在 JS 中的每个循环中的变量

[英]Scope of variable in a for each loop in JS

In the given react component sinppet, in the for each loop the compiler says that row is not defined, how can I fix this?在给定的反应组件 sinppet 中,在 for each 循环中,编译器说该行未定义,我该如何解决这个问题? data is of type object and columns is an array of strings数据是 object 类型,列是字符串数组

for(var row in data) {
                <tr>
                    {
                        columns
                            .map(column =>
                                (<td>{row[column]}</td>)
                            )
                    }
                </tr>
            }

Two issues with your code:您的代码有两个问题:

  1. In case you are trying to use this inside JSX, you will get rows as undefined because the for keyword cannot be used inside JSX.如果你试图在 JSX 中使用它,你将得到未定义的行,因为 for 关键字不能在 JSX 中使用。 You will need to map over the entries of the object as @Appaji pointed out.正如@Appaji 指出的那样,您需要 map 覆盖 object 的条目。

  2. When you say 'for var row in data', in every iteration of the loop, the value of row will be the key of data.当您说“for var row in data”时,在循环的每次迭代中,行的值将是数据的键。 Since you are trying to access the value of the row and not the key, you might want to change it to data[row].由于您正在尝试访问行的值而不是键,您可能希望将其更改为数据[行]。 Or you could you Object.values或者你可以 Object.values

So your code should look like所以你的代码应该看起来像

    Object.values(data).map(row => {
        <tr>
            {
                columns
                    .map(column =>
                        (<td>{row[column]}</td>)
                    )
            }
        </tr>
    })

Though, I'm not addressing the scope query here, I would do this as below.虽然,我不是在这里解决 scope 查询,但我会按以下方式执行此操作。 Tested CodeSandBox Link,Here经过测试的 CodeSandBox 链接,在这里

{Object.keys(data).map((row, index) => (
  <tr key={index}>
    {columns.map((column, _index) => (
      <td key={_index}>{data[row][column]}</td>
    ))}
  </tr>
))}

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

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