for循环的条件表达式每次迭代后是否变化?

Does condition expression of for loop changes after each iteration?

我正在尝试编写一个函数 decreasingOrder,它接受一个正整数作为输入,return 其数字的 array 以降序排列。

例如,decreasingOrder(1234) 应该给出 [4,3,2,1]

function decreasingOrder(n) {
  let unarr = [...`${n}`].map(i => parseInt(i)); //Unordered Array of Digits
  let oarr = []; //Ordered Array of Digits
  
  for(let j=0; j<unarr.length; j++){
  let max = Math.max.apply(Math, unarr);
  oarr.push(max);
  unarr.splice(unarr.indexOf(max), 1); //delete element from array
  }

  return oarr;
}

console.log(decreasingOrder(1234));
//Expected [4,3,2,1], Instead got [4,3]

因此,当我使用 splice 方法删除元素时,它会减少 unarr.length 并且当我尝试使用 delete 运算符保持 unarr.length 不变时,它会给出 NaN,我该怎么办?有没有其他方法可以写入相同的函数?我是 JavaScript.

的初学者

您的代码中的问题是 unarr.splice(unarr.indexOf(max), 1) 内部循环。

By taking your example of console.log(decreasingOrder(1234)). In the first cycle the highest number from the array is found and is removed from the array and pushed to new array.

At the end of the first cycle the outputs will be unarr = [1, 2, 3], oarr = [4] and j=1

Likewise after second loop unarr = [1, 2], oarr = [4, 3] and j=2. Now the loop condition j < unarr.length is not satisfied hence the loop breaks. So the output will be [4, 3].

您可以使用以下实用程序来满足您的要求。

function decreasingOrder(n) {
  let unarr = [...`${n}`].map(i => parseInt(i)) //Unordered Array of Digits

  return unarr.sort((a,b) => b-a)
}

console.log(decreasingOrder(1234))

希望这对您有所帮助。