简体   繁体   English

仅打印负数及其总和 aplaying 循环和数组

[英]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.负整数:-2, -1, -7 <----//末尾无逗号。

Sum negative nums: -10求和负数:-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.当我运行我的程序时,最后一个整数在末尾有一个额外的逗号,我不能用“if (i.= array.length-1)”把它去掉,因为我数组中的最后一个元素是正的,但是循环分析有一个空元素。 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.问题是当它应该是 Array.length-2 时,您只检查了 Array.length-1 的位置。 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.首先,上面的第 2 步没有太多逻辑意义,因为即使数字可能不是数组的最后一个元素,它也可能是数组的最后一个负数 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.如果将一个名为didOutput的布尔标志最初设置为false表示您是否曾输出过任何负数,那将更有意义。 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.只需得到一个像“first”这样的布尔值,它会检查它是否是第一个项目并将“,”放在你的数字之前。 You set it to true, after that you build stf like:您将其设置为 true,然后像这样构建 stf:

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

A simpler approach using filter , join and reduce :使用filterjoinreduce的更简单的方法:

 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.您的代码是使用 1995 年的语法和方法编写的。 document.write()不应像您正在使用的那样用于生成结果,而不是for循环,数组可以使用多种方法进行迭代。

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).在您的情况下,最好的方法是使用Array.filter()方法遍历原始数组,这会产生第二个值数组,这些值与您建立的某些条件相匹配(在本例中为负数)。 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.由于结果将在一个数组中,因此Array.join()方法将生成一个逗号分隔的字符串结果,您不必担心逗号的位置。 Then, you can sum the resulting array up with Array.reduce()然后,您可以将结果数组与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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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