Okay, trying to put together a numeric array and arrange it in ascending order. The more I look, the more I confuse myself. The alerts come up as "undefined." What am I overlooking?
好的,尝试将数字数组放在一起并按升序排列。我看的越多,我就越迷惑自己。警报显示为“未定义”。我在俯瞰什么?
var random = new Array();
function main() {
generate();
original();
ascending(random);
}
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = document.write(Math.floor(Math.random() * 100) + ", ");
}
}
function original() {
var storage = "";
for (var i = 0; i < 25; i++) {
storage += random[i] + ", ";
}
alert(storage);
}
function ascending(random) {
var tempArray = random;
var storage = "";
random.sort(function (a, b) {
return a - b
});
for (i = 0; i < 25; i++) {
storage += tempArray[i] + ", ";
}
alert("ASCENDING- " + storage);
}
2 个解决方案
#1
6
No need for document.write
(not sure what were you trying to achieve with it), this is enough:
不需要document.write(不确定你想用它实现什么),这就足够了:
random[i] = Math.floor(Math.random() * 100);
Afterwards, if you need to convert it to a string for output, just join it:
之后,如果您需要将其转换为字符串以进行输出,请加入:
random.join(",");
Here is your generate
function:
这是你的生成函数:
var random = [];
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = Math.floor(Math.random() * 100);
}
}
generate();
var str = random.join(', ');
document.write(str);
Note: try to avoid using document.write whenever you can.
注意:尽量避免使用document.write。
#2
2
Take out your document.write()
call in generate()
, that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.
在generate()中取出你的document.write()调用,在HTML文档中输出一个数字,直接将它分配给你的数组。您将该打印的结果分配给您的阵列,这绝对不是您想要的。
#1
6
No need for document.write
(not sure what were you trying to achieve with it), this is enough:
不需要document.write(不确定你想用它实现什么),这就足够了:
random[i] = Math.floor(Math.random() * 100);
Afterwards, if you need to convert it to a string for output, just join it:
之后,如果您需要将其转换为字符串以进行输出,请加入:
random.join(",");
Here is your generate
function:
这是你的生成函数:
var random = [];
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = Math.floor(Math.random() * 100);
}
}
generate();
var str = random.join(', ');
document.write(str);
Note: try to avoid using document.write whenever you can.
注意:尽量避免使用document.write。
#2
2
Take out your document.write()
call in generate()
, that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.
在generate()中取出你的document.write()调用,在HTML文档中输出一个数字,直接将它分配给你的数组。您将该打印的结果分配给您的阵列,这绝对不是您想要的。