2016-07-07 61 views
1

当我设置一些REST服务的匿名回调函数,我得到一个非常奇怪的行为,其中,如果我的REST服务的根本console.log的结果,我得到预期的有效载荷(一个对象数组)。然而,当我运行在同一个阵列上的循环,并尝试获得一些关键的价值,我得到一个错误,因为显然产品undefined不确定项打字稿for循环

... 
callback: (result) => { 
    console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}] 
    for(let item of result){ 
     console.log(item.text); // error can't read text of undefined 
     console.log(item); // HOWEVER... this works... :/ 
    } 
} 

任何想法?必须有某种异步行为发生,但我无法弄清楚。

谢谢!

+1

这不是一个错误打字稿,这仅仅是JavaScript的 –

+0

任何想法,为什么我得到这个错误?由于 –

+0

[一切似乎工作(https://www.typescriptlang.org/play/index.html#src=var%20result%20%3D%20%5B%7Btext%3A%20'foo'%7D% 2C%20%7Btext%3A%20'bar '%7D%5D%3B%0D%0Aconsole.log(结果)%3B%20%2F%2F%20outputs%20%5B%7Btext%3A%20'foo' %7D%2C%20%7Btext%3A%20'bar'%7D%5D%0D%0Afor(让%20item%20of%20result)%7B%0D 0A%%20%20%20%20console.log(项目的.text)%3B%20%2F%2F%20error%20can't%20read%20text%20of%20undefined%0D 0A%%20%20%20%20console.log(项目)%3B%20%2F%2F %20HOWEVER ...%20this%20works ...%20%3A%2F%0D 0A%%7D)如预期。你确定'response'确实是在评论中吗? – martin

回答

1

这不是你如何遍历数组。你应该用一个完整的for循环或forEach功能:

for(let i = 0, l = result.length; i < l; i++) { 
    console.log(result[i].text); 
} 

result.forEach((item) => { 
    console.log(item); 
}); 
+2

他环路的版本工作完全正常了打字稿操场(它被transpiled你的第一个例子是这样),但是+1的'forEach'。 – rinukkusu

+0

谢谢,我会试试看。尽管它在操场上运行良好,但它必须与REST服务的结果有关。可能与回复承诺和迭代之前他们真正得到完整的回应,但不知道。我是新来的TypeScript,所以不知道如何调试。 –

+1

这条规则适用于使用'for ... in','for ... of'与集合一起工作 – martin

2

你最有可能有畸形的阵列。下面是一个说明问题的例子:

// Malformed array 
const result = [ 
    {text: 'foo'}, 
    {text: 'bar'}, 
] 
result.length = 3; 

// Your code 
console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}] 
for(let item of result){ 
    console.log(item.text); // error can't read text of undefined 
    console.log(item); // HOWEVER... this works... :/ 
} 

修复

  • 过滤掉空项。

更多提示

  • 的console.log将打印不合理的东西,一个空行。你可能不会看到在您的调试
  • 阅读上的JavaScript阵列孔
  • 享受生活