简体   繁体   English

将数组中的数字相乘并以文字和点表示法添加到对象

[英]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. 如果使用文字符号,则无法像obj = {num[i] : num[i]*2}那样定义对象。点符号obj.num[i] = num[i] * 2不能正常工作文字和点表示法中的键必须是实际的字符串。 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 – jharclerode

On a browser that supports Object.defineProperty (ECMA5) you also have this alternative, if you really must. 在支持Object.defineProperty (ECMA5)的浏览器上,如果确实需要,也可以使用此替代方法。

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 jsFiddle上

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

相关问题 通过一串点表示法在对象文字中设置深度? - Setting a depth in an object literal by a string of dot notation? 将对象文字符号转换为数组 - Convert object literal notation to array 使用Java语言中的文字表示法将对象插入数组 - Insert an Object into an Array using Literal Notation in Javascript 数组在对象文字表示法中添加函数 - array adding function in object literal notation 无法使用点符号或索引器符号向对象添加属性? - Unable to add a property to an object using either the dot notation or the indexer notation? 使用点表示法访问数组或类似数组的对象的元素 - Access elements of an array or array-like object using the dot notation Javascript 命名空间 - 从对象文字表示法 (OLN) 更新数组值 - Javascript namespacing - updating an an array value from an object literal notation (OLN) Cloud Firestore:使用点表示法更新嵌套数组对象中的字段值 - Cloud firestore: Update field values in nested array object with dot notation 如何将点符号字符串数组转换为对象 JavaScript 并呈现到表格? - How to convert dot notation string array into an object JavaScript and render to table? 对象文字符号中的“literal”是什么意思? - What is the meaning of “literal” in the phrase object literal notation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM