StevenC
StevenC

Reputation: 75

Strange results with javascript array.length function

I have piece of JavaScript code which cycles through form elements and builds an object. I have a mixture of HTML input fields and ASP.NET input fields. ASP.NET changes the ID of the fields to the form xxxxx_yyyy_id, so I am attempting to use the split function to extract the original id.

 // Iterate over all the text fields and build an object
 $(':text').each(function () {

     var tokens = this.id.split("_");
     if (tokens.length = 3) {
         // Assume this is a .net inputbox - extract the original id
         inFormData[tokens[2]] = this.value;
     } else {             
         inFormData[this.id] = this.value;
     }
 });

Stepping through the above code, the first id is ctl00_ContentPlaceHolderCol1_forenameField, so the tokens.length = 3 code is run. On the second iteration, the id is forenameField2 so I would expect the tokens.length to be 1, but it is actually 3. The else statement is never run.

This could be something simple, but I cant work it out. If I inspect the tokens array it has only 1 element in on the second iteration. I have also tried setting the array.length to 0 after each iteration.

Any help appreciated.

Upvotes: 1

Views: 520

Answers (4)

Jay Blanchard
Jay Blanchard

Reputation: 34406

That is why you should always put the constant first when testing. If you forget a comparison sign it will throw an error:

if( 3 = tokens.length ) // throws an error
if( 3 == tokens.length ) // ok
if( 3 === tokens.length) // ok

Upvotes: 2

Alnitak
Alnitak

Reputation: 339786

Change your = 3 to === 3

At the moment you're overwriting tokens.length every time.

NB: === is preferred to == because it's an exact equality check. The two-equals version will attempt to cast the two operands to the same type before comparison, which is 1. unnecessary, 2. inefficient, 3. sometimes error prone.

Upvotes: 2

Alex
Alex

Reputation: 35399

from:

if (tokens.length = 3) {

to:

if (tokens.length == 3) {

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

Correct this:

== instead of =. === is more better


     if (tokens.length == 3) {
         // Assume this is a .net inputbox - extract the original id
         inFormData[tokens[2]] = this.value;
     } else {             
         inFormData[this.id] = this.value;
     }

Upvotes: 4

Related Questions