我正在编写一些JavaScript,从1到9中取出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!")
JavaScript代码:
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);
}
我得到的错误:
Expected: 10 9 8 7 6 5 4 3 2 1 liftoff!, instead got: undefined
为什么未定义?
答案 0 :(得分:4)
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!';
}
答案 1 :(得分:0)
这里还有一个选项可以满足您的需求:
<强> 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>
<强>的JavaScript 强>
var countdown = document.getElementById("btnCountdown");
var instructions = [5, 3, 2, 6, 4, 1, 9, 7, 8];
countdown.onclick = function () {
var sortedInstructions = instructions.sort();
for (var i = instructions.length - 1; i >= 0; i--) {
var text = document.createTextNode(sortedInstructions[i]);
var el = document.createElement("P");
el.appendChild(text);
document.body.appendChild(el);
if (i == 0) {
var liftOff = document.createTextNode("Lift Off!");
var lastEl = document.createElement("P");
lastEl.appendChild(liftOff);
document.body.appendChild(lastEl);
}
}
}