Calculate the total in array

时间:2017-12-18 08:05:24

标签: javascript arrays sum

I'm trying to write a code which calculate the total of an array length of 3. Each 3 integers are from prompt.

Right now my code is like the following:

iperf -uVZc 192.168.0.1 -b400m

However when I see the result it seems that this

var num1 = prompt("First number");
var num2 = prompt("Second number");
var num3 = prompt("Third number");

var new_array = [num1, num2, num3]

function sum_three(new_array)
    {
        return new_array[0] + new_array[1] + new_array[2];
    }

document.write(sum_three(new_array));

part does not calculate, it just concatenate the numbers. How do I make work?

2 个答案:

答案 0 :(得分:1)

Inputs entered by your keyboard are strings. If you use 'addition' dates = '' for data in elem.find_all('span', class_='TextRun'): dates.join([dates, data.text]) on strings, you concatenate them. You have to convert (parse) the numbers contained in your string to an actual javascript number.

One simple way of doing it is by adding a + in front of each string variable. It will try it best to 'interpret' your strings as numbers

+

Actually, the correct technical term is 'coercion', thanks @NeilDocherty, more info here https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md)

Simple example exhibiting the behavior :

return +new_array[0] + +new_array[1] + +new_array[2];

You can also use console.log("3" + "5"); // outputs 35 console.log(+"3" + +"5"); // outputs 8, as you already did.

There are differences between the two, see for example this post : parseInt vs unary plus - when to use which

In particular, parseInt will return parseInt for an empty string whilst NaN will coerce it as + .

答案 1 :(得分:0)

A more modern solution would be to use the Array.prototype.reduce method.

I find this more readable, but if you are going to support browsers older than IE9, then you will need to polyfill it in.

function getContentTypeOfCurrentItem(id) {
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
  listItem = oList.getItemById(id);
  clientContext.load(listItem);
  listContentTypes = oList.get_contentTypes();
  clientContext.load(listContentTypes);
  return clientContext.executeQueryAsync(
    function() {
      $log.info("Successfully retrieved getContentTypeOfCurrentItemt");
      var ctid = listItem.get_item("ContentTypeId").toString();
      var ct_enumerator = listContentTypes.getEnumerator();
      while (ct_enumerator.moveNext()) {
        var ct = ct_enumerator.get_current();
        if (ct.get_id().toString() == ctid) {
          var contentTypeName = ct.get_name();
        }
      }
      return Promise.resolve(contentTypeName);
    },
    function(error, errorInfo) {
      $log.warn("Retrieving getContentTypeOfCurrentItem failed");
      deferred.reject(errorInfo);
    }
  );
}