我正在尝试使用 javascript 按升序对数字进行排序,但我被卡住了。 HTML:
<h2>JavaScript Array Sort</h2>
<p>Click the button to sort the array in ascending order.</p>
<button onclick="myFunction()">I will arrange</button>
<p id="demo"></p>
</body>
JS:
var points = [7, 1, 6, 3, 5, 2];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
js fiddle 链接:https://jsfiddle.net/djmayank/uef3xexk/
我没有弄错。感谢任何形式的帮助。
最佳答案
除非使用 No wrap - in <body>
,否则您需要使用事件处理程序调用该函数JSFiddle 中的选项。
JS
var submit = document.querySelector('#submit')
var output = document.getElementById('demo')
var points = [40, 100, 1, 5, 25, 10];
output.innerHTML = points;
function sortArray() {
points.sort(function(a, b) {
return a - b
});
output.innerHTML = points;
}
submit.addEventListener('click', function(event) {
event.preventDefault()
sortArray()
})
HTML
<h2>JavaScript Array Sort</h2>
<p>Click the button to sort the array in ascending order.</p>
<button id="submit">I will arrange</button>
<p id="demo"></p>
JSFiddle 演示:https://jsfiddle.net/uef3xexk/3/
关于Javascript按升序排列不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552847/