这是我在做算法题是遇到的关于for of的一个问题
var findDisappearedNumbers = function (nums) {
// 将遍历到的项放回该去的地方,当该去的地方已经有对应数,将当前数的下标+1放入数组
const res = []
for (let [i, num] of nums.entries()) {
while (num !== i + 1 && nums[num - 1] !== num) {
swap(nums, i, num - 1)
console.log(i, num);
}
}
for (const [i, num] of nums.entries()) {
if (num !== i + 1) res.push(i + 1)
}
return res
function swap(nums, index1, index2) {
const temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp
}
};
nums = [4, 3, 2, 7, 8, 2, 3, 1]
console.log(findDisappearedNumbers(nums));问题描述:
while并没有像我想的那样一直执行,当把for of换成for 就可以完成while,请问是为什么
10
收起

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星