提问人:Rafael 提问时间:4/2/2014 更新时间:4/2/2014 访问量:25
传递到回调中的 JavaScript 访问数组属性
javascript access array properties passed into a callback
问:
通过回调函数,如何访问字符串数组的每个值的属性?我希望能够使用 Array#filter 来保留长度小于 x 的字符串。
var arr1 = [
'Tempor quis esse consequat sunt ea eiusmod.',
'Id culpa ad proident ad nulla laborum incididunt.',
'Ullamco in ea et ad anim ulam est.',
'Est ut irure irure nisi.'
];
这是我的过滤功能:
var arr2 = arr1.filter(function(value, index, array) {
return value.length < x;
});
唉,我收到一条 TypeError 消息,内容为”TypeError: Cannot read property 'length' of undefined
"
我所要做的就是让我的回调返回长度小于 x 个字符的字符串。我做错了什么?
答:
0赞
Phaedra
4/2/2014
#1
您的代码正在工作,显然没有定义 x,但我假设您在外部上下文中定义了 x,因此在过滤器回调中,它可用于闭包。
你在哪里运行此代码?
在上一个firefox控制台中,它运行良好。
评论