passing array value using closure

被刻印的时光 ゝ 提交于 2019-12-11 06:39:23

问题


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.



来源:https://stackoverflow.com/questions/15212604/passing-array-value-using-closure

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