-1

I want to create a dictionary in javascript like this

var operations=
{  
  first:     function(x) 
             {
                return x[0];
             }
}

How can I add the + operation as key to the dictionary that will point to the + operation in javascript? The same thing was done in python by operator.add . How can do it in Javascript?

var operations=
{  
     +    :     return + operation in javascript //syntax is not valid

     first:     function(x) 
                 {
                    return x[0];
                 }
}  

.

Meta_Data
  • 13
  • 4

2 Answers2

1

Use "+"

var operations=
{  
     "+"    :     return + operation in javascript //syntax is not valid

     first:     function(x) 
                 {
                    return x[0];
                 }
}  
void
  • 36,090
  • 8
  • 62
  • 107
1

Though question is not very clear, but as per my understanding, use function, like

var data = [1,2,3,4,5,6];

var operations=
{  
     "+"    :    function (x){ return x.reduce(function(p,n,ar,i) { return p+=n }, 0) },

     first:     function(x) 
                 {
                    return x[0];
                 }
} 

console.log("SUM: " + operations["+"](data));

console.log("FIRST: " + operations.first(data))
A.T.
  • 24,694
  • 8
  • 47
  • 65
  • i just want to get the + operation in javascript.. The same thing done in python by operator.add ... – Meta_Data Nov 07 '16 at 06:24
  • '+' operators work in two ways in JS, adding values or concatenation , how will you decide what operation to call – A.T. Nov 07 '16 at 06:27
  • @A.T.— the [*unary + operator*](http://ecma-international.org/ecma-262/7.0/index.html#sec-unary-operators) also does type conversion to number. ;-) – RobG Nov 07 '16 at 06:55
  • @Meta_Data check the edited one, to add values in an array – A.T. Nov 07 '16 at 07:03