我的代码中有一个奇怪的问题
我有类似
的东西var test, result;
$(".class td").each(function(){
test = $(this).find('input').attr('size');
if(test){
result = test * 10;
}
console.log(result);
})
并非每个td
都有输入字段,因此test
可能是undefined
。但是,在定义测试后,控制台将始终从test
输出值。
例如:
undefined (test = undefined)
undefined (test = undefined)
undefined (test = undefined)
200 (test = 20)
200 (test = undefined)
200 (test = undefined)
200 (test = undefined)
我不确定这里发生了什么。有人可以帮我吗?感谢。
答案 0 :(得分:4)
在内部范围中定义result
而不是将其保留在外部范围内,因为第一个结果具有值,您的进一步迭代仍然保留旧值,这就是您所看到的。
$(".class td").each(function(){
var result ,
test = $(this).find('input').attr('size');
if(test){ //remove this check and you will see NaN for the iterations where test = undefined in your code
result = test * 10;
}
console.log(result);
});
您还可以避免循环没有输入字段的td。
$(".class td:has(input)").each(...
或
$(".class td:has(input[size])").each(...
答案 1 :(得分:0)
您可以抓住选择器中的输入,并将每个项目的结果映射到数组:
var result = $('.class td input').map(function() {
return $(this).attr('size') * 10;
}).toArray();