需要一些帮助才能完成使用成功函数的Javascript程序。我找不到用变量替换return语句的方法,所以我可以在第二个函数中使用varable。
程序使用语句findArrayparts(myArray1, myArray2)
来使函数findArrayparts(myArray1, myArray2)
生成一个随机整数,该整数小于其中一个数组(等长)的数组长度。
然后在函数findArrayparts(myArray1, myArray2)
中使用此随机整数来计算出相应的数组元素,并将它们放入一个数组中,然后显示在一个警告框中。
<SCRIPT SRC = glossary.js></SCRIPT>
<SCRIPT language = "JavaScript">
var myVar1;
var myVar2;
var myVar3;
var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow'];
var myArray2 = ['tomatoe', 'orange', 'apples', 'blueberry', 'banana'];
// generates random integer and assigns result to myVar1
function getNumberRand(aNum)
{
//return Math.floor(Math.random() * aNum);
myVar1 = Math.floor(Math.random() * aNum);
}
function findArrayparts(myArray1, myArray2)
{
// calls getNumberRand function
getNumberRand(myArray1.length);
// works out characters at same index in both arrays
myVar2 = (myArray1(myVar1));
myVar3 = (myArray2(myVar1));
// new array to hold output
outputArray = new Array(myVar2, myVar3);
// display output
outputArray.join();
alert(outputArray);
}
// Calls findArrayparts function
findArrayparts(myArray1, myArray2);
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
答案 0 :(得分:2)
DEMO: http://jsfiddle.net/PjtxY/
var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow'];
var myArray2 = ['tomatoe', 'orange', 'apples', 'blueberry', 'banana'];
function getNumberRand(aNum) {
return Math.floor(Math.random() * aNum);
}
function findArrayparts(myArray1, myArray2) {
// Store return value in local variable
var random_num = getNumberRand(myArray1.length);
// Use [] square brackets to get array member
var myVar2 = myArray1[ random_num ];
var myVar3 = myArray2[ random_num ];
// Store new Array in local variable.
var outputArray = new Array(myVar2, myVar3);
// Store joined result in a variable
var result = outputArray.join();
// Alert the result
alert( result );
}
findArrayparts(myArray1, myArray2);
答案 1 :(得分:0)
你在注释掉的行中有它。只需返回值:
function getNumberRand(aNum)
{
return Math.floor(Math.random() * aNum);
}
答案 2 :(得分:0)
您在评论之前已经getNumberRand
了。您想要返回随机数:
function getNumberRand(aNum)
{
return Math.floor(Math.random() * aNum);
}
然后,当您想要稍后使用该函数的返回时,只需将结果赋值给变量:
function findArrayparts(myArray1, myArray2)
{
// calls getNumberRand function
var myVar1 = getNumberRand(myArray1.length);
// works out characters at same index in both arrays
myVar2 = (myArray1(myVar1));
myVar3 = (myArray2(myVar1));
...
}
答案 3 :(得分:0)
为什么使用全局变量myVar1,myVar2,myVar3?使用return
从函数中获取值。
这是你想要实现的目标:
<script type="text/javascript">
var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow'];
var myArray2 = ['tomato', 'orange', 'apples', 'blueberry', 'banana'];
function getNumberRand(aNum)
{
return Math.floor(Math.random() * aNum);
}
function findArrayparts(myArray1, myArray2)
{
var index = getNumberRand(myArray1.length);
alert(outputArraymyArray1[index] + ', ' + myArray2[index]);
}
findArrayparts(myArray1, myArray2);
</script>