JavaScript。 10%5 === 0 --> 错误?

JavaScript. 10%5 === 0 --> false?

请帮忙找出我代码中的错误:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false 

显然,我很期待

console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, true 

谢谢!

当数组中有多个值相同时,问题在于 indexOf - array.indexOf(10) 始终是 4,请在此处查看扩展日志:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item,array.indexOf(item),item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

解决方法是使用forEach index参数(第2个) https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

function multipleOfIndex(array) {
    return array.forEach( (item,idx) => console.log(item%idx === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

[indexOf] 方法 returns 可以在数组中找到给定元素的第一个索引。如果不存在,则 returns - 1。 所以最后10个的[indexOf]值为4.