passing array value using closure

2019-08-02 09:15发布

问题:

Whats the best way of getting multiple local arrays from another function. I am doing something similar to this. And as far as the variable names attached to a function, "arr1=f1()", do these need to be declared as local ,"var arr1=f1()".

<script>

    function ArrValues(arr){
        var array=arr;
        function f1(){
            var ID=[];
            ID=['grapes','peaches','plums'];
            return ID
        };
        function f2(){
            var Nam=[]; 
            Nam=['car','motorcycle','tree'];
            return Nam
        };
        function f3(){
            var Num=[]; 
            Num=['200','1000','350'];
            return Num
        };

        if(array=='one' || array=='all'){ arr1=f1()};
        if(array=='two' || array=='all'){ var arr2=f2()};
        if(array=='three' || array=='all'){ var arr3=f3()};

        gotIt(arr1,arr2,arr3)
    }

    function gotIt(arr1,arr2,arr3){
        alert(arr1);
        alert(arr2);
        alert(arr3);
    }

</script>

<div id="one" onclick="ArrValues(this.id)">one</div>
<div id="two" onclick="ArrValues(this.id)">two</div>
<div id="three"onclick="ArrValues(this.id)">three</div>
<div id="all"onclick="ArrValues(this.id)">all</div>

回答1:

Well that depends. Since you are passing the values to gotIt directly, it doesn't look like you need them globally so should have var on all of them.

That said, your code is quite messy and a little redundant. Try this:

function ArrValues(arr) {
    var arr1 = arr=='one' || arr=='all' ? ['grapes','peaches','plums'] : [],
        arr2 = arr=='two' || arr=='all' ? ['car','motorcycle','tree'] : [],
        arr3 = arr=='three' || arr=='all' ? ['200','1000','350'] : [];
    gotIt(arr1,arr2,arr3);
}

Note that I've given each one a default value of an empty array, otherwise you would end up with undefined variables.