user991735
user991735

Reputation: 682

How to pass Array/Values to a Javascript function

I am learning Javascript for a project using online resources however i don't know how to get this function working.

var results =[[a1,a2,a3,a4,a5]];
var winner = 0;

function checkWinner (results)
{ 
  for (var i = 0; i < results.length; i++)
    if (results[0][i] > 50)
    {
      winner = results[0][i];

    }
}

Just after the function, i use: checkWinner(results);

In a HTML file i use alert to display the variable winner. But it obviously doesn't work. I realise it is a problem with my understanding of scope and global variables.

Upvotes: 1

Views: 8575

Answers (3)

nogola
nogola

Reputation: 214

You're iterating over the result[0] array (the array in result[0]), but using the length of the result array.

Upvotes: 1

NullUserException
NullUserException

Reputation: 85468

You've got to understand the concept of scope. The variables results and winner are not the same inside and outside the function.

Also, you've got to call the function and return something from it if you want to change the value of the variables outside the function (unless you use globals). This seems to be hard for novice programmers to understand, but merely defining a function doesn't do anything.

var results =[[a1,a2,a3,a4,a5]];

function checkWinner (results)
{ 
    for (var result in results[0]) 
    {
        if (result > 50)
        {
            return result;
        }
    }
}

var winner = checkWinner(results);

Note that:

  • I used a for each loop, which has a cleaner syntax.
  • I am also iterating over results[0] instead of results, since you've got a nested array for whatever reason.
  • Because your function has an argument called results, it requires you to pass the global results in spite of it being a global. Another way to do this:

var results = [[a1,a2,a3,a4,a5]];

function checkWinner()
{ 
    for (var result in results[0]) 
    {
        if (result > 50)
        {
            winner = result;
            return;
        }
    }
}

checkWinner();

However, I would recommend against using global variables this way. Here's an explanation on why global variables are bad. It's for C++, but it applies to JavaScript as well.

Upvotes: 1

Oybek
Oybek

Reputation: 7243

should be

var Results =[[a1,a2,a3,a4,a5]];
var winner = 0;

function checkWinner (results)
{ 
  for (var i = 0; i < results[0].length; i++)
    if (results[0][i] > 50)
    {
      winner = results[0][i];

    }
}

checkWinner(Results);

To avoid name collisions name global variables from capital case. Also in your code you call the length of the "parent" array. You need to specify the length of the "Child" array

Upvotes: 3

Related Questions