如何从函数中获取Array值?
这有效:
var days = new Array();
days[1] = 'Sunday';
days[2] = 'Monday';
days[3] = 'Tuesday';
days[4] = 'Wednesday';
days[5] = 'Thursday';
days[6] ='Friday';
days[7] = 'Saturday';
alert(days[3]); // returns Tuesday
但是如果我把它放在一个函数中,我如何让alert()工作?
function mydays(){
var days = new Array();
days['Sunday'] = 1;
days[8] = 'Monday';
days[3] = 'Tuesday';
days[4] = 'Wednesday';
days[5] = 'Thursday';
days[6] ='Friday';
days[7] = 'Saturday';
}
alert(mydays(days[8])) //nothing should be Monday
alert(days[8]) // nothing should be Monday
正确的语法是什么? 谢谢。
答案 0 :(得分:1)
变量days
已在函数mydays
的范围内声明,您无法从外部访问它。但是,您有一些选择:
这似乎是你想要的alert(mydays(days[8]))
。你不需要传递参数,只需:
function mydays() {
var days = new Array();
days['Sunday'] = 1;
days[8] = 'Monday';
days[3] = 'Tuesday';
days[4] = 'Wednesday';
days[5] = 'Thursday';
days[6] = 'Friday';
days[7] = 'Saturday';
return days; // return the whole array
}
alert(mydays()[8]) // get the 8th element of the array returned
var days = new Array(); // empty array
function mydays() {
days['Sunday'] = 1;
days[8] = 'Monday';
days[3] = 'Tuesday';
days[4] = 'Wednesday';
days[5] = 'Thursday';
days[6] = 'Friday';
days[7] = 'Saturday';
}
alert(days[8]) // days is still empty array, we haven't called the function yet
mydays(); // will set the days' values
alert(days[8]) // will be now monday
希望它有所帮助!
答案 1 :(得分:0)
从函数中获取任何值的方式相同:返回它。你没有返回数组,因此它会被创建并立即消失。
答案 2 :(得分:0)
尝试
<script>
function mydays(index) {
var days = new Array();
days['Sunday'] = 1;
days[8] = 'Monday';
days[3] = 'Tuesday';
days[4] = 'Wednesday';
days[5] = 'Thursday';
days[6] = 'Friday';
days[7] = 'Saturday';
return days[index];
}
alert(mydays(8));
</script>