英文:
How to print only even numbers in a JS array?
问题
我无法弄清楚如何从数组中仅打印偶数:
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
我尝试了几种变化,但它们都不起作用:
while (i < arrayAgeList.length) {
for (i = 1; i < arrayAgeList.length; i++)
if (i % 2 === 0)
}
}
英文:
I cant figure out how to print only even numbers from an array:
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
I have tried a few variations, but they dont work:
while (i < arrayAgeList.length) {
for (i = 1; i < arrayAgeList.length; i++)
if (i % 2 === 0)
}
}
答案1
得分: 0
我建议创建一个函数来实现这个,并且要打印出结果,你需要做类似于控制台日志的操作。
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
function even(list){
for(var i of list){
if (i % 2 === 0){
console.log(i)
}
}
}
even(arrayAgeList)
英文:
I would suggest creating a function to achieve this and to print you'll need to do something like a console log
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
function even(list){
for(var i of list){
if (i % 2 === 0){
console.log(i)
}
}
}
even(arrayAgeList)
</details>
# 答案2
**得分**: 0
需要声明变量 `i` 并使用单个 `for` 循环,从零开始,因为索引是从零开始的。
在检查中,你需要使用值而不是索引,如果条件为 `true`,则输出该值。
```javascript
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24],
i;
for (i = 0; i < arrayAgeList.length; i++) {
if (arrayAgeList[i] % 2 === 0) console.log(arrayAgeList[i]);
}
请注意,这段代码是用 JavaScript 编写的,用于遍历数组 arrayAgeList
中的元素,并打印出其中偶数值。
英文:
You need to declare i
and take a single for
loop and start with zero, because the index is zero based.
For the check, you need the value isntead of the index and if true
make an output with the value.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24],
i;
for (i = 0; i < arrayAgeList.length; i++) {
if (arrayAgeList[i] % 2 === 0) console.log(arrayAgeList[i]);
}
<!-- end snippet -->
答案3
得分: 0
var evenNumbers = arrayAgeList.filter(currentNumber => currentNumber % 2 === 0)
英文:
var evenNumbers = arrayAgeList.filter(currentNumber => currentNumber % 2 === 0)
答案4
得分: 0
你可以使用 Array.filter
来筛选数组,只保留偶数年龄,然后可以直接打印它。
const arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
const even = num => num % 2 === 0;
const evenAges = arrayAgeList.filter(even);
evenAges.forEach(age => console.log(age));
英文:
You can use Array.filter
in order to filter the array and remain only even ages, then you can just print it.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
const even = num => num % 2 === 0;
const evenAges = arrayAgeList.filter(even);
evenAges.forEach(age => console.log(age));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论