如何将if语句的结果放入我可以稍后返回的新数组中
How to place the results of an if statement into a new array which I can return later
我对代码相当陌生,我被一个特定的问题困了很长一段时间。我觉得我已经很好地掌握了问题所需要的东西,但是我无法弄清楚如何将if语句的结果返回到一个新的数组中,然后我可以返回。如有任何帮助或建议,我将不胜感激。
function loveTheThrees (myArray) {
var myTotal = 0;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 3 === 0) {
myTotal += myArray[i];
/* What I'm looking to do at this stage of the problem is place the results into a new array which will be returned rather than myTotal */
}
}
return myTotal; // Placed this here just to test to see if the problem would post the results
}
loveTheThrees ([1, 3, 5, 12, 21]);
您可以使用Array#filter
。
function loveTheThrees(myArray) {
return myArray.filter(function (a) {
return a % 3 === 0;
});
}
console.log(loveTheThrees([1, 3, 5, 12, 21]));
试试这个:
function loveTheThrees (myArray) {
var newarray = []
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 3 === 0) {
newarray[newarray.length] = myArray[i]
}
}
return newarray;
}
loveTheThrees ([1, 3, 5, 12, 21]);
这样回答你的问题了吗?它取除3(%3)后没有余数的任何项,并将其放入数组newarray中,并返回它。
带箭头函数表达式:
var loveTheThrees = (myArray) => myArray.filter(element => element % 3 === 0);
console.log(loveTheThrees([1, 3, 5, 12, 21]));
相关文章:
- 对象数组返回自最近日期以来的最高总体值
- csv数据中的新数组
- javascript函数,它将数组作为输入,将每个数组元素增加1,并返回增加值的新数组
- 按值名称过滤掉重复的对象,并将其放入新数组中
- 根据对多个数组唯一的元素创建一个新数组
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 从多维数组返回嵌套数组
- Javascript-在一个数组中搜索整个单词,并创建一个符合条件的新数组
- 为什么当我点击<a>使用纯javascript;这个“;返回url,数组返回“url”;未定义”;
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 为什么将元素推送到 concat( ) 返回的新数组中会返回数组的大小而不是数组本身
- 比较两个数组并返回一个新数组,其中包含仅在其中一个原始数组中找到的任何项目
- 如何将数组元素拆分为2,并返回一个已拆分原始元素的新数组
- 在Javascript中搜索由整数组成的数组并返回带有值的新数组
- 创建一个方法来编辑原始数组,而不是返回一个新数组
- 返回数组中value的每个唯一实例,在一个新数组中
- JScript:将字符串数组作为输入,返回只包含少于5个字符的字符串的新数组
- 在JavaScript中,将数组的每个值映射到给定的函数以返回一个新数组
- Javascript循环一个对象数组并返回一个新数组
- 如何将if语句的结果放入我可以稍后返回的新数组中