console.log(5 % 2); //5 = 2 * 2 + 1
console.log(8 % 3); //8 = 2 * 3 + 2
console.log(6 % 2); //6 = 2 * 3 + 0
console.log(7 % 2); //7 = 2 * 3 + 1
● 我们可以利用这个特性来判断一个数是奇数还是偶数
const isEven = n =>
n % 2 === 0 ? console.log(`${n}是偶数`) : console.log(`${n}是奇数`);
isEven(5);
isEven(8);
实例
● 通过奇数偶数判断,将奇数行赋予一种颜色,将偶数行赋予另一种颜色
labelBalance.addEventListener('click', function () {
[...document.querySelectorAll('.movements__row')].forEach(function (row, i) {
i % 2 === 0
? (row.style.backgroundColor = 'orangered')
: (row.style.backgroundColor = 'blue');
});
});