首页 > 解决方案 > 使用“for of loop”而不是“for loop”的排序算法挑战 - 问题

问题描述

我已经使用 for 循环解决了一个算法,但是我一直在尝试使用 for of 循环,以使其更易于阅读,但是当我使用传统的 for 循环时,我没有得到相同的输出?

const sortByHeight = (a)=>{

const array2 = a.filter(num => {
    if (num !== -1){
        return num
    }
}).sort((a,b) => a-b)

let indexVal = 0;

for ( let num of a){
     if(num !== -1 ){
         num = array2[indexVal]
         indexVal++
     }
 }


return a;

 //for loop does work
//     for ( let i=0; i < a.length; i++){
//     if(a[i] !== -1 ){
//         a[i] = array2[indexVal]
//         indexVal++
//     }
// }
// return a;

console.log(sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]));}

标签: arraysfor-loopfor-of-loop

解决方案


num是循环内的局部变量。分配给它不会更改数组中的相应元素。这类似于分配给函数参数对传递给函数的参数没有影响的方式。

你最好的选择就是像以前一样坚持索引数组。for...of当您想遍历数组并读取它时使用。它不允许像您尝试那样覆盖元素。

如果您真的想使用for...of,您可以压缩数组以使用另一个索引数组进行排序,以便在需要时进行索引,但此时您将失去任何可读性优势for...of


推荐阅读