如何从数组中确定负数,以获取所有正数之和? [英] How to target the negative numbers from an array, to get the sum of all the positive numbers?

查看:60
本文介绍了如何从数组中确定负数,以获取所有正数之和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何以数组中的负数为目标.我有这个:

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 do I target (ignore) all negative numbers in an array, when I don't know how many negative numbers are in the array?

例如,我试图遍历整个数组,找到正数,将它们存储在另一个数组中,然后求和:(1 + 2 + 3 + 4 + 5 + 10 + 23).

For example, I am trying to loop through the entire array, find the positive numbers, store them in another array, and then get the sum: (1+2+3+4+5+10+23).

如果可能的话,我只想使用本地js.

If possible I want to do this only with native js.

推荐答案

只需创建一个条件来检查它是正数还是负数,然后定义一个空数组 negatives ,并且该数是否为负数如果正值将其推入负数数组,将其添加到 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);

这篇关于如何从数组中确定负数,以获取所有正数之和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆