如果我在 Math.abs() 中传递数组,我无法理解为什么它返回 -3,为什么我的值从正变为负
let test1 = [2, 3, 3, 1, 5, 2]
let test2 = [2, 4, 3, 5, 1]
function firstDuplicate(a) {
for (let i of a) {
console.log(i);
let posi = Math.abs(i) - 1;
//console.log(posi);
}
}
console.log(firstDuplicate(test1))
console.log(firstDuplicate(test2))
我不明白 Math.abs 是如何工作的,真正的代码如下
function firstDuplicate(a) {
for (let i of a) {
let posi = Math.abs(i) - 1
if (a[posi] < 0) return posi + 1
a[posi] = a[posi] * -1
}
return -1
}
最佳答案
Math.abs() 返回数字的绝对值。但是你将你的绝对值乘以负1。这就是为什么你得到负值
a[posi] = a[posi] * -1
关于javascript - Javascript 中的 Math.Abs() - 数组意外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431266/