Javascript:将数组传递给函数不起作用?

时间:2014-09-16 19:44:43

标签: javascript

我有一个用push构建数组的函数。

function one(resultsArray) {
    activity_basic_weight = 9;
        for (i in resultsArray) {
            score = 0;
            score = resultsArray[i].var_a * activity_basic_weight;
            score = Math.round(score * 100) / 100;
            if (score >= 80) 
            {
                verygoodCategories1.push({
                    score: score,
                    name: i,
                    url: resultsArray[i].url
                });
            } 
            else if (score <= 79) 
            {
                ...         
            }
        }

    two(verygoodCategories1, ...);      
}

function two(verygoodCategories1, ...) {

    alert(verygoodCategories1.length); //  = 7, correct;

    // here comes the problem:

    for (var i = 0; i < verygoodCategories1.length; i++) {
        //this throws "Error: TypeError: verygoodCategories1 is undefined"
    }
}

我是Javascript的新手。我做了一些根本错误的事吗?

这是伪代码,但我确保至少变量名称是正确的等等。

有什么想法吗?

由于

Ĵ

3 个答案:

答案 0 :(得分:1)

将数组参数分配给变量:

function two(verygoodCategories1, ...) {

    alert(verygoodCategories1.length); //  = 7, correct;

    var goodCategories=verygoodCategories1;
    var goodCategoriesLength=goodCategories.length;
    for (var i = 0; i < goodCategoriesLength; i++) {
        console.log(goodCategories[i]);
    }
}

答案 1 :(得分:1)

声明变量很重要。 另外,正如评论中所提到的,不要用于... in。也许有一天你会想要使用它,但不是今天。

这是您编写的伪代码,以便它可以实际工作。

var a = [{var_a:100},{var_a:90},{var_a:81},{var_a:81},{var_a:91},{var_a:101}];
function one(resultsArray) {

    //This is critical to later using it as an array.
    var verygoodCategories1 = [];

    // you should always initialize a variable with var.  
    // You can not do it but thats bad form. You will
    // pollute the global space and people will dislike you.
    var activity_basic_weight = 9;
    for (var i = 0; i < resultsArray.length; i++) {
        var score = resultsArray[i].var_a * activity_basic_weight;
        score = Math.round(score * 100) / 100;
        if (score >= 80) 
        {
            verygoodCategories1.push({
                score: score,
                name: i,
                url: resultsArray[i].url
            });
        } 
        else if (score <= 79) 
        {
            //...
        }
    }

    two(verygoodCategories1); 
}

function two(verygoodCategories1) {

    alert(verygoodCategories1.length); //  = 7, correct;

    for (var i = 0; i < verygoodCategories1.length; i++) {
        //no more errors!
    }
}

one(a);

答案 2 :(得分:0)

转到function one(resultArray)。就在for之前,你可能想要在那里声明数组:

verygoodCategories1 = new Array();