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