【发布时间】:2018-05-05 23:44:24
【问题描述】:
如果我在 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
}
【问题讨论】:
-
请添加结果和想要的结果。
-
请注意你乘以 -1 a[posi] = a[posi] * -1
标签: javascript arrays typescript ecmascript-6