0

早些时候我发布了一个关于访问存储在函数中的数组值,
使用闭包传递数组值的问题,并被告知这段代码可以完成这项工作。

<script>
    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);
  }

 function gotIt(arr1,arr2,arr3){
    alert(arr1);
    alert(arr2);
    alert(arr3);
  }
</script>

我已经更新了代码,如下所示。这是只返回我想要的数组而不将其作为参数发送给另一个函数的好方法吗?

  <script>
  function ArrValues(arr) {
  var arr1 = arr=='one' || arr=='all' ? ['grapes','peaches','plums'] : [];
  if(arr1.length>0){
    return arr1;
  };

  arr2 = arr=='two' || arr=='all' ? ['car','motorcycle','tree'] : [];
  if(arr2.length>0){
    return arr2;
  };

 arr3 = arr=='three' || arr=='all' ? ['200','1000','350'] : [];
  if(arr3.length>0){
    return 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>
4

2 回答 2

2

怎么样

function ArrValues(arr) {
    var values = {
         'one': ['grapes','peaches','plums'],
         'two': ['car','motorcycle','tree'],
         'three': ['200','1000','350']
        };

    return values[arr];
}

(it does not handle the all case as you do not describe what to return in this case..)


if with all you want all values merged in a single array then

function ArrValues(arr) {
    var match,
        values = {
            'one': ['grapes','peaches','plums'],
            'two': ['car','motorcycle','tree'],
            'three': ['200','1000','350']
        };

     if (arr!=='all'){
         match = values[arr];
     } else {
         match = values['one'].concat( values['two'] ).concat( values['three'] );
     }

     return match;
}
于 2013-03-06T03:09:01.347 回答
1

并不真地。由于您对“其他”案例不感兴趣,因此您最好这样做:

if( arr == "one" || arr == "all") return ['grapes','peaches','plums'];

和类似的构造。

话虽如此,如果你这样做,那么所谓的“all”按钮将永远只返回“one”数组,因为它总是匹配第一个if语句并返回数组。

于 2013-03-06T03:01:50.253 回答