我试图在JS中按升序排列一些数字,但它似乎无法工作,我得到以下控制台日志:[1,2,3,6,9,1,2,3,4,6, 8,9,12,18,18,24,36,72]
以下是代码:
var firstNum = 18;
var secondNum = 72;
var array = [];
var otherArray = [];
for (i = 0; i <= firstNum; i++) {
if(firstNum % i === 0) {
array.push(i);
}
}
for (j = 0; j <= secondNum; j++) {
if(secondNum % j ===0) {
array.push(j);
}
}
for (k = 0; k < array.length; k++) {
if(array[k] > array[k+1]) {
var temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
console.log(array)
console.log(otherArray)
感谢帮助。
答案 0 :(得分:0)
您可以像这样修改代码:
for (i = 0; i <= arrayX.length-1; i++)
{
if (arrayX[i] > arrayX[i+1])
{
temp = arrayX[i+1];
arrayX[i+1] = arrayX[i];
arrayX[i] = temp;
i = i-2;
}
}
var firstNum = 18;
var secondNum = 72;
var array = [];
var otherArray = [];
for (i = 0; i <= firstNum; i++) {
if (firstNum % i === 0) {
array.push(i);
}
}
for (j = 0; j <= secondNum; j++) {
if (secondNum % j === 0) {
array.push(j);
}
}
for (i = 0; i <= array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
i = i - 2;
}
}
alert(array)
&#13;
希望它可以帮助你:)
答案 1 :(得分:0)
Use otherArray also like
for (j = 0; j <= secondNum; j++) {
if(secondNum % j ==0) {
otherArray.push(j);
}
}
then print by using the same logic of temp it will give individual array output in ascending order and if you want to join two array output then use concat/merge and then print