JavaScript倒计时循环
我正在编写一些JavaScript来获取一个由9个从1到9的数字组成的数组,这些数字是无序的,并以字符串形式返回从10到1的倒计时 例如: 输入:[4,9,3,10,6,8,2,7,1,5] 输出:“10 9 8 7 6 5 4 3 2 1发射!” JavaScript测试:JavaScript倒计时循环,javascript,arrays,loops,testing,Javascript,Arrays,Loops,Testing,我正在编写一些JavaScript来获取一个由9个从1到9的数字组成的数组,这些数字是无序的,并以字符串形式返回从10到1的倒计时 例如: 输入:[4,9,3,10,6,8,2,7,1,5] 输出:“10 9 8 7 6 5 4 3 2 1发射!” JavaScript测试: Test.assertEquals(liftoff([2, 8, 10, 9, 1, 3, 4, 7, 6, 5]),"10 9 8 7 6 5 4 3 2 1 liftoff!") function liftoff(i
Test.assertEquals(liftoff([2, 8, 10, 9, 1, 3, 4, 7, 6, 5]),"10 9 8 7 6 5 4 3 2 1 liftoff!")
function liftoff(instructions){
var countdown = "";
var start = 10;
for (start; start >= 1; start--) {
for (var i = 0; i < instructions.length; i++) {
if (instructions[i] == start) {
var count = instructions[i].toString();
countdown += count + " ";
}
}
}
countdown += " liftoff!";
console.log(countdown);
}
JavaScript代码:
Test.assertEquals(liftoff([2, 8, 10, 9, 1, 3, 4, 7, 6, 5]),"10 9 8 7 6 5 4 3 2 1 liftoff!")
function liftoff(instructions){
var countdown = "";
var start = 10;
for (start; start >= 1; start--) {
for (var i = 0; i < instructions.length; i++) {
if (instructions[i] == start) {
var count = instructions[i].toString();
countdown += count + " ";
}
}
}
countdown += " liftoff!";
console.log(countdown);
}
为什么它未定义?这里还有一个选项可以满足您的需求:
function liftoff(instructions) {
return instructions
// sort into correct order
.sort(function(a, b){
return b - a;
})
// convert into string with spaces
.join(' ') +
// add 'lift off!
' lift off!';
}
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="Countdown" id="btnCountdown"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
instructions=liftf[4,9,3,10,6,8,2,7,1,5]是什么意思?问题是什么?你调用过这个函数吗?有错误吗?他似乎想对一个数组进行数字排序,并在最后保持升空,但并不像OP说的那样,因为帖子提到的输入是1-9,倒数从10降到1。但是…这也没什么意义,所以我会给出和你差不多的答案。