嘿,我正在为作业编写代码而且我被卡住了。我的问题是我想找到满足条件的数组中最大的有效数字,数字在[0,500]之间,可以被5或3整除。这就是我到目前为止所做的:
var numlist =[];
var count = 0 ;
var bignum;
while (count >= 0) {
bignum = Number(prompt("Enter Number"));
if (bignum == 12345){
break;
}
if (bignum > 500 || bignum < 0){
document.write("No data to Print");
continue;
}
if (!(bignum % 3 === 0 || bignum % 5 === 0)){
document.write("No data to Print");
continue;
}
numlist = Math.max(bignum);
bignum = numlist;
var loop;
for (loop = 0; loop <= 10; loop++){
value = bignum * loop;
document.write(bignum + " X " + loop + " = " + value + "<br />");
}
}
有人能帮助我吗?
答案 0 :(得分:0)
在这里,这是一种方法。我试图尽可能地改变它,所以你可以做到这一点&#34;你的方式&#34;。请稍微研究一下这段代码,然后随意问你是否理解不了解。
var numlist = [];
var bignum;
// get the number and populate the array
while (true) { // you don't need a var if you want an infinite loop
bignum = Number(prompt("Enter Number"));
if (bignum == 12345) {
break;
}
if (bignum > 500 || bignum < 0) {
continue;
}
if (!(bignum % 3 == 0 || bignum % 5 == 0)) {
continue;
}
numlist.push(bignum); // push method in an array includes a value
}
if (numlist.length == 0) {
document.getElementById('res').innerHTML = "No data to Print";
} else {
var max = -Infinity;
for(var ix = 0; ix<numlist.length; ix++) {
if (numlist[ix] > max) max = numlist[ix];
}
var content = '';
for (var loop = 0; loop <= 10; loop++) {
value = max * loop;
content += max + " X " + loop + " = " + value + "<br />";
}
document.getElementById('res').innerHTML = content;
}
&#13;
<div id="res"></div>
&#13;
这是一个更高级的版本,供您在javascript时学习::)
var numlist = [], bignum;
while ((bignum = Number(prompt("Enter Number"))) != 12345)
((bignum > 0) && (bignum < 500)) && (!(bignum % 3) || !(bignum % 5)) &&
numlist.push(bignum);
var max = Math.max(...numlist)
document.getElementById('res').innerHTML =
numlist.length && [...Array(11).keys()].reduce((p, _ign, ix)=>
p += max + " X " + ix + " = " + (max * ix) + "<br />", '') || 'No data to Print';
&#13;
<div id="res"></div>
&#13;