How to pass Array/Values to a Javascript function

依然范特西╮ 提交于 2019-12-08 03:52:39

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/8081741/how-to-pass-array-values-to-a-javascript-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!