如何从数组中定位e负数,得到所有正数的总和? [英] How to target e negative number from an array, and get the sum of all positive numbers?
问题描述
我试图找出如何在数组中定位负数。
我有这个
I am trying to figure it out how to target negative numbers in an array. I have this
function SummPositive( array ) {
}
SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );
这是一个带负数和正数的数组。如何定位数组中的所有负数,当你不知道数组中有多少负数?
This is an array with negative and positive numbers.How to target all negative numbers from array, when you don't know how many negative numbers are in array?
例如,我正在尝试来...循环
到整个数组,找到正数,将它们存储在另一个数组中,并将总和(1 + 2 + 3 + 4 + 5 + 10 + 23)
。
For example, I am trying to...loop
to entire array, find the positive numbers, store them in another array, and make a sum (1+2+3+4+5+10+23)
.
但我是菜鸟,我不知道怎么做。
如果可能只使用原生js
But i am noob, and i don't how to do that. If possible to do this only with native js
推荐答案
只要条件检查它是正面的还是负面的数字,然后定义一个空数组负数
如果数字是负数,则将其推入负数数组中,如果为正,则将其添加到 sum
变量,检查下面的工作示例。
Just make a condition to check if it's a positive or negative number, then define an empty array negatives
and if the number is negative push it inside negatives array if positive add it to sum
variable, check working example below.
function SummPositive( numbers ) {
var negatives = [];
var sum = 0;
for(var i = 0; i < numbers.length; i++) {
if(numbers[i] < 0) {
negatives.push(numbers[i]);
}else{
sum += numbers[i];
}
}
console.log(negatives);
return sum;
}
var sum_result = SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );
console.log(sum_result);
这篇关于如何从数组中定位e负数,得到所有正数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!