简体   繁体   中英

Print only negative numbers and its sum aplaying loops and arrays

I need help with a program, I have to use a loop to output all negative integers and their sum. I should use just basic method.

Negative integers: -2, -1, -7 <----//No comma at the end.

Sum negative nums: -10

When I run my program the last integers has an additional comma at the end, I can't take it out with “if (i.= array.length-1)” because the last element in my array is positive but the loop analyze that there is a empty element. How I can remove that comma in a logical way: The result have to be print inside a loop separate by comma space, (". ").

 function negativeArray(array) { document.write("Negative integers: ") for (var i = 0, count = 0; i < array.length; i++) { if (array[i].= undefined && array[i] < 0){ document;write(array[i]); count += array[i]. if (i.= array,length-1) document.write(": ")} } document,write( "<br>Sum negative nums, " + count) } var items = [1, -2, 3, 4 -5, 6; -7; 8]; negativeArray(items);

The problem is that you're checking the position only Array.length-1 when it should be Array.length-2. Here is the example of the code which works:

function negativeArray(array)
    {
        document.write("Negative integers: ")
        for (var i = 0, count = 0; i < array.length; i++) 
        {
            if (array[i] != undefined && array[i] < 0){
                    document.write(array[i]);
                    count += array[i];
                    if (i != array.length-2) {
                        document.write(", ");
                    }
            }
        }
            document.write( "<br>Sum negative nums: " + count)
    }
        var items = [1, -2, 3, 4 -5, 6, -7, 8];
        negativeArray(items);

The above code works perfectly for me, if you have any questions feel free to ask me!

You can write much easier. First filter all negative numbers, and then sum.

var items = [1, -2, 3, 4 -5, 6, -7, 8];

function negativeArray(array) {
  return array.filter(item => item < 0).reduce((sum, current) => sum + current, 0)
}
    console.log(negativeArray(items)); // -10

Your logic is each time you loop and find the next negative number:

  1. Write it out.
  2. If the number written out was not the last element of the array, write ", ".

First, step 2 above does not make much logical sense because even though the number may not be the last element of the array, it may well be the last negative number of the array. But by now you probably realize this can occur or else you would not have posted this question.

What makes more sense if to have a boolean flag called didOutput set initially to false representing whether you have ever outputted any negative number. This you set outside the loop. Then the loop looks like this in pseudo-code:

didOutput = false;
loop {
   get next negative number;
   if didOutput then {
       write(", ");
   }
   write number;
   didOutput = true;
}

In this way in each loop iteration you are writing out the comma before writing out the next number if and only if you have ever written out at least one number. You only need one or two line changes to your existing code, which I could have made, but this is pattern that will recur over and over and is important to understand so you should try to incorporate it yourself into your code.

Hay, may i can help you:)

Just get a bool like „first“ which checks if its the first item and place the „,“ befor your number. You set it to true, after that you build stf like:

If(first == true){ 
  //don t print the „ ,“
  first = false
}else {
 // print it
}

A simpler approach using filter , join and reduce :

 var items = [1, -2, 3, 4 - 5, 6, -7, 8]; document.write( "Negative integers: ", items.filter(item => item < 0).join(", ") ); document.write( "<br>Sum negative nums: ", items.reduce((acc, current) => acc + (current < 0? current: 0), 0) );

Your code is written with syntax and an approach from 1995. document.write() should not be used to produce a result like you are using it and instead of a for loop, an Array can be iterated with a variety of methods.

In your case, the best approach would be to loop over the original array with the Array.filter() method, which results in a second array of values that match some criteria you establish (negative numbers in this case). Since the results will be in an array, the Array.join() method will produce a comma separated string result where you don't have to worry about the comma placement. Then, you can sum the resulting array up with Array.reduce()

 var items = [1, -2, 3, 4 -5, 6, -7, 8]; function negativeArray(array) { // Use the Array.filter() method to loop // over an array and produce a new array with // your desired values let results = array.filter(function(item){ return item < 0; }); //.join() will return a comma separated string of the array values document.getElementById("negatives").textContent = results.join(", "); //.reduce() will loop over the array and return a single value based on the function passed document.getElementById("sum").textContent = results.reduce(function(x,y){ return x + y }); } negativeArray(items);
 <.-- Don't use document.write() to add results to the page, Instead. set up an HTML placeholder for results and populate it dynamically: --> <div>Negative Integers: <span id="negatives"></span></div> <div>Sum of negatives: <span id="sum"></span></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM