将条件应用于阵列 [英] Applying conditions to an Array
问题描述
我在申请条件后申请返回数组时遇到问题.
I have a problem applying to return an array after applying a condition.
在这里,
使用给定的数组:[1、2、3]
With a given array: [1, 2, 3]
条件1:如果是奇数,应乘以* 2.
Condition 1: If it is an Odd, should multiply *2.
条件2:如果它是偶数,则将其返回.
Condition 2: If it is an Even, just return it.
期望的结果:[2,2,6]
这是我的方法;
Here is my approach;
function oddToEven(array) {
var evens = [array];
var odds = [array];
if (array %2 !== 0){
array *2;
return odds;
} else {
return evens;
}
}
oddToEven(1,2,3); // returns => [1]
我知道这很基本,当然我的方法是错误的,但这是我学习JS的第一周,希望你们中的一些能给我带来启发!
I know this is pretty basic, and surely my approach is all wrong, but this is my very first week learning JS, I hope some of you give me a light on this!
非常感谢
推荐答案
使用 .map
将一个数组转换为另一个数组-每次调用回调函数返回的内容将是新数组中的相同索引:
Use .map
to transform one array into another - what is returned from each call of the callback function will be the item in the same index in the new array:
const oddToEven = array => array.map(
num => num % 2 === 1 ? num * 2 : num
);
console.log(oddToEven([1, 2, 3]))
或者,更详细些:
function oddToEven(array) {
return array.map(function(num) {
if (num % 2 === 1) // Odd
return num * 2;
else // Even (or not an integer)
return num;
}
}
当然,这假定原始数组中的每个项目都是整数.
Of course, this assumes that every item in the original array is an integer.
这篇关于将条件应用于阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!