arrays - 使用“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]));
}
解决方案
num
是循环内的局部变量。分配给它不会更改数组中的相应元素。这类似于分配给函数参数对传递给函数的参数没有影响的方式。
你最好的选择就是像以前一样坚持索引数组。for...of
当您想遍历数组并读取它时使用。它不允许像您尝试那样覆盖元素。
如果您真的想使用for...of
,您可以压缩数组以使用另一个索引数组进行排序,以便在需要时进行索引,但此时您将失去任何可读性优势for...of
。
推荐阅读
- r - 用结果在 r 中分割文件 ANOVA
- ios - 带有大标题的 UISearchController 在选项卡栏中崩溃,“只有一个带有顶部边界的调色板可以在过渡之外处于活动状态”
- reactjs - UI 状态与 Redux 状态
- node.js - nodejs中的车把助手不起作用
- ios - Appcelerator 钛图像在列表视图中的 IOS 中向下或向上滚动时消失
- c# - 使用 TraceSource 跟踪和记录到文件
- r - 使用 R 分析的 Django Web 应用程序
- ruby - Rubocop atom linter 不起作用
- java - 程序在数组中找到最不常见的条目
- python - 使用“def”API 时的 Python - 不返回任何内容(或错误)