FlyingCat
FlyingCat

Reputation: 14260

Weird issue on Jquery .each function

I have a weird issue in my codes

I have something like

var test, result;
$(".class td").each(function(){
     test = $(this).find('input').attr('size');
     if(test){
         result = test * 10;
     }
     console.log(result);
})

not every td has a input fields so test could be undefined. However, the console will always output a value from the test after test is defined.

For example:

   undefined (test = undefined)
   undefined (test = undefined)
   undefined (test = undefined)
   200 (test = 20)
   200 (test = undefined)
   200 (test = undefined)
   200 (test = undefined)

I am not sure what's going on here. Can someone help me out? Thanks.

Upvotes: 0

Views: 128

Answers (2)

PSL
PSL

Reputation: 123739

Define result in the inner scope rather than holding it in the outer scope, since the first result has value your further iterations still holds the old value and that is what you see.

$(".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);
});

You can also avoid looping the td that doesn't have input fields.

$(".class td:has(input)").each(...

or

$(".class td:has(input[size])").each(...

Upvotes: 4

elclanrs
elclanrs

Reputation: 94101

You could just grab the inputs in the selector, and map the result of each item to an array:

var result = $('.class td input').map(function() {
  return $(this).attr('size') * 10;
}).toArray();

Upvotes: 0

Related Questions