[英]How do I get a toggle button to toggle an array back and forth from descending to ascending?
I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. 我正在使用bubbleSort,我可以使数组从其原始顺序切换到降序,但是我很难使它从降序回到升序。 Should I just copy the bubbleSort code and flip the greater than/less than signs?
我应该只复制bubbleSort代码并翻转大于/小于符号吗? Any help is appreciated!
任何帮助表示赞赏!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going. 首先,您需要一个拨码来告诉您要走的路。
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement. 然后在if语句上方的for语句内的bubbleSort函数中。
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with: 然后,将if语句替换为:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable: 最后,完成排序后,您可以切换变量:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead. 不过,我建议您使用切换变量,而只需使用sort()和reverse()即可。
https://jsfiddle.net/ytcax0qc/ https://jsfiddle.net/ytcax0qc/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.