根据输入向数组添加值,求和或减去

时间:2016-07-07 02:07:33

标签: javascript arrays

每次用户输入一个整数时我都要创建一个新的输入文本,那些整数应该添加到一个数组中,最后程序必须根据值加总或减去。

例如,如果数组是这样的:[1, 5, 10],最终结果为:16但如果数组如此[2, 3, 7, -1, 5],则最终结果应为7 ,为什么?这是因为您总结2 + 3 + 7然后减去5

我现在面临的主要问题是我的代码出了问题而没有做最后的计算。

一些代码:

var arrayOfNumbers = [];
var column = 1;

function logingValues (){

    var values = $('input[name^=valuesToSum]').map(function(idx, elem) {
            newVal = $(elem).val();
            if (isNaN(newVal)) {
              newVal = 0;
            }
            return newVal;
    }).get();

    console.log("Values aquired from inputs " + values);

    arrayOfNumbers = values;

    console.log("Values inserted on Array " + arrayOfNumbers);
}


function removeElement (id){
    $('#' + id ).remove();
    console.log("element #" + id + " was eliminated");
}

function iterateOverArray(array){

   var oldArray = array;
   var newArray = "";

   for (var i = 0; i < oldArray.length; i++) {
      newArray += " + " + oldArray[i];
   }

   return newArray;
}

function addElement (whereToPrint){

    logingValues();

    var newArray = iterateOverArray(arrayOfNumbers);

    var printId = "print" + whereToPrint;

    console.log(printId);

    console.log("we can see the array like this " + arrayOfNumbers);

    $('#'+ printId).html(newArray);

    console.log('Element was created');


      column += 1;

      var newInput  =  // here goes a template

      $('.elemPlaceHold').append(newInput);

}

function loadingBar (){

    var summingBar = '<div class="rect1"></div><div class="rect2"></div><div class="rect3"></div><div class="rect4"></div><div class="rect5"></div>';

    $('.spinner').append(summingBar);
}

function caculationEffect (countTotal){

    $('#result').html("");
    loadingBar();


    setTimeout(function(){

        $('.spinner').html("");
        $('#result').html(countTotal);
    }, 2000);
}

function calculate (){

    console.log("is calculating....");

    logingValues();
    // Variable to hold your total 
    var countTotal = 0;  
    // Variable that states how the process start (sum/subtract)
    var conditional = true;
    var changeCondition;

    for(var i = 0; i < arrayOfNumbers.length; i++) {

        if(arrayOfNumbers[i] === -1){
            changeCondition = conditional ? conditional = false : conditional;
        }else{
            if(conditional === true){
               countTotal += arrayOfNumbers[i];
            }else{
               countTotal -= arrayOfNumbers[i];
            }
        }
      }
    console.log('countTotal', countTotal);
    caculationEffect('countTotal', countTotal);
}

Here is a JSBin

有什么建议吗?

修改

唯一要考虑的是:在进行计算之前,如果数组中有-1,那么它应该减去。否则总结!

6 个答案:

答案 0 :(得分:2)

这里有一些问题。

  • 1)caculationEffect只应该countTotal,但你传递的是caculationEffect('countTotal', countTotal)
  • 2)您试图使用arrayOfNumbers类似的字符串,您必须先将它们转换为数字。

请尝试使用以下代码:

var total = 0;
var shouldSubtract = false;
for (var i = 0; i < arrayOfNumbers.length; i++) {
    if (arrayOfNumbers[i] == "") continue;
    var currentNumber = parseInt(arrayOfNumbers[i], 10);
    if (currentNumber === -1) {
        shouldSubtract = true;
    } else {
        if (shouldSubtract) {
            total -= currentNumber;
            shouldSubtract = false;
        } else {
            total += currentNumber;
        }
    }
}
caculationEffect(total);

答案 1 :(得分:1)

解决方案很简单,如果你做一个简单的console.log(arrayOfNumbers);,你会发现你的值存储为字符串。

日志示例: ["3", "4"]

由于您使用===运算符,JavaScript还会比较值的类型。实际上,“ - 1”=== -1返回false。这就是为什么你永远不会达到“changeCondition”代码的原因。

使用parseInt()函数将“字符串”转换为数字,您的问题将得到解决。

答案 2 :(得分:1)

试一试:

<html>
    <head>
        <meta charset="utf-8">
        <style>
        </style>
    </head>
    <body>
        <script>
           var arr = [2, 3, 7, -1, 5];
            function calculate(arr) {
                total = 0;
                if(arr.length > 0) {
                var index = arr.indexOf(-1);
                if (index === -1){
                    for(var i = 0;i <arr.length;i++)
                        total += arr[i];
                    }
                else {
                    for(var i=0 ; i<arr.length;i++) {
                        if(i===index)
                            continue;
                        if(i < index)
                            total+=arr[i];
                        else
                            total-=arr[i];  
                    }  
                }
            }
                return total;
            }
            alert (calculate(arr));
        </script>
     </body>
</html>

答案 3 :(得分:1)

执行减法后需要重置条件值。所以改变

        if(arrayOfNumbers[i] === -1){
            changeCondition = conditional ? conditional = false : conditional;
        }else{
            if(conditional === true){
               countTotal += arrayOfNumbers[i];
            }else{
               countTotal -= arrayOfNumbers[i];
            }
        }

        if(arrayOfNumbers[i] === -1){
            changeCondition = conditional ? conditional = false : conditional;
        }else{
            if(conditional === true){
               countTotal += arrayOfNumbers[i];
            }else{
               countTotal -= arrayOfNumbers[i];
               conditional = true;
            }
        }

答案 4 :(得分:1)

1)数组是一个字符串数组,因此你得到连接

    var values = $('input[name^=valuesToSum]').map(function(idx, elem) {
            newVal = $(elem).val();
            if (isNaN(newVal)) {
              newVal = 0;
            }
            return parseInt(newVal); // parseInt or parseFloat
    }).get();

2)你正在传递&#34; countTotal&#34;作为参数[0]而不是实际值

caculationEffect('countTotal', countTotal);


function caculationEffect (title, countTotal){ // add title argument

    $('#result').html("");
    loadingBar();

    setTimeout(function(){
        $('.spinner').html("");
        $('#result').html(countTotal);
    }, 2000);
}

答案 5 :(得分:1)

您可以执行以下计算:

function calculate(array) {
  return array.reduce(function(prev, curr, i, arr) {
    if(curr === -1) {
      arr[i+1] *= -1;
      return prev;
    }
    return prev + curr;
  });
}

演示:

function calculate(array) {
  return array.reduce(function(prev, curr, i, arr) {
    if(curr === -1) {
      arr[i+1] *= -1;
      return prev;
    }
    return prev + curr;
  });
}

console.log(calculate([2, 3, 7, -1, 5]));
console.log(calculate([2, 3, 7, -1, 5, -1, 2]));
console.log(calculate([2, 3, 7]));