chobo2
chobo2

Reputation: 85845

How to pass a integer into a javascript function?

I am getting a response from ajax request(done by jquery).

I have a method that displays errors to the users. Sometimes though I have some other information coming along with the json request.

So I don't want this info shown(where the rest of the errors are). So I figured since I always know the length of the json coming back I can just shorten the length since the error method just uses a while loop so if it is one less then it won't display that json part.

So I did this

var length = result.length -1;

ErrorsMethod(result, length); // call function.

   function ErrorsMethod(result, length)
    {
       while( i < length)
       { 
         // do stuff.
       }
    }

length is always undefined when it gets passed in though. I don't understand why.

I then tried

length.length ParseInt(length);

None seems to work. I don't even know what I am working with. When I do an alert of "length" var before it goes into the function it spits out a number.

Upvotes: 2

Views: 34667

Answers (3)

kripto_ash
kripto_ash

Reputation: 919

nor result or i are defined variables so thats probably why the script stops executing. try something like this:

<script type="text/javascript">
    var result = [10, 2];
    var length = result.length;


    ErrorsMethod(result, length); // call function.

    function ErrorsMethod(result, length)
    {
       var i=0;
       while( i < length)
       { 
         // do stuff.
         alert(i);
         i++;
       }
    }

</script>

Upvotes: 0

w35l3y
w35l3y

Reputation: 8783

ErrorsMethod(result); // call function.

function ErrorsMethod(result)
{
    if (result && result.length)
    for ( var i = 0 ; i < result.length ; ++i )
    { 
        // do stuff.
    }
}

Upvotes: 1

karim79
karim79

Reputation: 342695

Were you correctly calling parseInt?

var length = parseInt(result.length) - 1;
ErrorsMethod(result, length);

ErrorsMethod(result, length); // call function.

   function ErrorsMethod(result, length)
    {
       while( i < length)
       { 
         // do stuff.
       }
    }

Upvotes: 5

Related Questions