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