I'我试图创建一个函数,将范围(0-100)内的三个数字随机化,并打印最大的一个
I'm trying to create a function that Randomizes three numbers in range (0-100) and prints the largest one
。。。但当我在控制台中调用函数时,它返回未定义的结果。我是一个JavaScript新手,所以我可能犯了一个基本错误,如果有人能帮我,我会很高兴的:-)。
这是代码:
var randomPrint = function(){
x = Math.floor(Math.random() * 100);
y = Math.floor(Math.random() * 100);
z = Math.floor(Math.random() * 100);
console.log(x, y, z);
if(x > y && x > z)
{
console.log("The greatest number is" + " " + x);
}
else if(y > z && y > x)
{
console.log("The greatest number is" + " " + y);
}
else if(z > y && z > x)
{
console.log("The greatest number is" + " " + z);
}
};
randomPrint();
理智的方式:
var nums = [];
for (var i = 0; i < 3; i++) {
nums.push(Math.floor(Math.random() * 100));
}
console.log('Largest number is ' + Math.max.apply(null, nums));
或者:
nums = nums.sort();
console.log('Largest number is ' + nums[nums.length - 1]);
是的,函数将返回undefined
,因为您不会从函数返回任何内容。很可能你的条件都不匹配,所以你也看不到任何其他输出。
试试这个内置的方法来获得最大
Math.max(x,y,z);
如果你能扔掉另外两个数字:
for (var i = 0, max = -Infinity; i < 3; ++i) {
max = Math.max(Math.floor(Math.random() * 100), max);
}
alert(max);
decze的答案是一个更好的解决方案,但我认为您也在工作。控制台中的输出示例为:
35 50 47
The greatest number is 50
undefined
未定义的部分是因为函数没有返回任何内容。你可以把它写成
var randomPrint = function(){
x = Math.floor(Math.random() * 100);
y = Math.floor(Math.random() * 100);
z = Math.floor(Math.random() * 100);
console.log(x, y, z);
if(x > y && x > z) {
var biggest = x;
console.log("The greatest number is" + " " + x);
} else if(y > z && y > x) {
console.log("The greatest number is" + " " + y);
var biggest = y;
} else if(z > y && z > x) {
console.log("The greatest number is" + " " + z);
var biggest = z;
}
return biggest;
};
randomPrint();
var randomPrint = function(){
x = Math.floor(Math.random() * 100);
y = Math.floor(Math.random() * 100);
z = Math.floor(Math.random() * 100);
console.log(x, y, z);
console.log("this is max " +Math.max(x,y,z);)
}();
你的逻辑也没有错。未定义可能会出现在其他地方,这很好。
88 36 15 localhost/:16最大的数字是88
这是我得到的你的代码的输出。
相关文章:
- 使用javascript将动态表从一个html页面打印到另一个html页
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- $.每个jquery循环打印一个“;未定义的“;对于getJSON请求后的每个元素,网格数据都会完美地打印出来
- 如何要求用户输入一个介于 1 和 50 之间的整数,然后小程序打印出一行这个星数
- 从一个复杂的JSON对象打印每个JSON输入路径
- Javascript:将多个表单输入打印到一个文本区域
- 我如何做一个纯Javascript foreach循环并打印出结果firebase
- 将NG打印的数据在一个html中重复传输到另一个html
- 如果我只想从数组中打印任何一个元素.任何数组.那么代码会是什么
- Grails:多个加载ajax调用,但只有一个打印到控制台
- 打印regex之后的最后一个字符
- For循环只打印一个DIV标记.不是8个DIV标签
- 创建一个bookmarklet,可以检索文本框的所有最大长度,然后在表中打印id和最大长度
- 计算特定日期's将日期更改为另一个日期,并打印它们的差异
- 如何在HTML中打印一个特定的Javascript变量
- 我有两个问题!一个是打印,另一个是缩放
- 打印出字符串中所有单词的最后一个字符
- 如何编写一个测试来验证函数是否已成功将字符串列表(在数组中指定)打印到屏幕上
- 从右到左打印一个三角形
- 如何在Chrome或Firefox的JavaScript控制台中引用最后一个打印出来的对象