观察以下函数。
function PermutationStep(num) {
var max = Number(String(num).split('').sort((a,b)=>b-a).join(''))
console.log(max); // 9431
for(var i = num; i < max; i++){
let perm = Number(String(i).split('').sort((a,b) => b-a).join('')) === max;
console.log(perm);
if(i > num && perm) { // I don't understand why this returns 9314 as opposed to the max since perm is set equal max.
return i;
}
}
return -1;
}
console.log(PermutationStep(9143));
它的设计目的是获取一个数字,然后找到该数字的下一个排列。例如。 9143 应返回 9314。
我理解除了一行之外的代码; if 语句。如果最大值 === 9431 为什么函数返回 9314 作为排列?
最佳答案
因为这一行:
let perm = Number(String(i).split('').sort((a,b) => b-a).join('')) === max;
...获取 9143 (i
) 的数字并将它们重新排列为最高的在前,然后转换回数字。该数字是 9431,即 max
,因此由于 9431 === 9431
为 true
,因此 perm
为 true 。然后,在该 if
中,满足 i > num
(9314 > 9143
为 true
)并且 perm
为 true
,因此满足条件。
关于javascript - 设置为严格相等变量的变量返回 true,但函数返回的数字小于它等于的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730395/