要从偶数位置访问数字,而不是遍历数字,请遍历位置, 即index。如果我们遍历数字,而不是偶数元素,则将访问偶数。
在以下示例中,使用for循环遍历所有位置,并使用空字符串访问偶数位置值。该 条件语句“如果”是用来检查位置是偶数与否。如果有任何位置,则通过空字符串访问对应于该位置的值,并显示为输出。
<html>
<body>
<script>
var nums = [15,23,63,53,58,66,77,29,2,110];
for(var i = 0; i< nums.length; i++) {
var dis = "";
if((i + 1) %2 === 0) {
dis = dis + (nums[i]) + "</br>";
document.write("Digit in " +(i + 1)+ " place is " + " "+dis);
}
}
</script>
</body>
</html>Digit in 2 place is 23 Digit in 4 place is 53 Digit in 6 place is 66 Digit in 8 place is 29 Digit in 10 place is 110