简体   繁体   中英

Multiply numbers in array and add to an object in literal and dot notation

Just wondering how to do this code in literal and dot notation

function multi(num){
  var obj = {};
  for(var i = 0; i < num.length; i++){
    obj[num[i]] = num[i] * 2;

  }
  return obj;  
}

If you use literal notation you cannot define the object like so obj = {num[i] : num[i]*2} same goes for dot notation obj.num[i] = num[i] * 2 will not work seeing as the key in literal and dot notation needs to be an actual string. Is there a way to define the key of an object as the current number and the value the current number multiplied by two of an object with literal or dot notation?

so not doable in any other notation besides bracket? – jharclerode

On a browser that supports Object.defineProperty (ECMA5) you also have this alternative, if you really must.

function multi(num) {
    var obj = {};
    for (var i = 0; i < num.length; i++) {
        Object.defineProperty(obj, num[i], {
            value: num[i] * 2,
            enumerable: true
        });
    }
    return obj;
}

var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(multi(nums));

On jsFiddle

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