简体   繁体   English

在javascript中返回键/值对

[英]Returning key/value pair in javascript

I am writing a javascript program, whhich requires to store the original value of array of numbers and the doubled values in a key/value pair. 我正在编写一个JavaScript程序,要求将数字数组的原始值和双精度值存储在键/值对中。 I am beginner in javascript. 我是javascript的新手。 Here is the program: 这是程序:

var Num=[2,10,30,50,100];
var obj = {};

function my_arr(N)  
{
    original_num = N
    return original_num;

}



function doubling(N_doubled)
{
   doubled_number = my_arr(N_doubled);

   return doubled_number * 2;
}   


for(var i=0; i< Num.length; i++)
 {
    var original_value = my_arr(Num[i]);
    console.log(original_value);
    var doubled_value = doubling(Num[i]);
    obj = {original_value : doubled_value};
console.log(obj);
}

The program reads the content of an array in a function, then, in another function, doubles the value. 程序读取一个函数中数组的内容,然后在另一个函数中将该值加倍。

My program produces the following output: 我的程序产生以下输出:

2
{ original_value: 4 }
10
{ original_value: 20 }
30
{ original_value: 60 }
50
{ original_value: 100 }
100
{ original_value: 200 }

The output which I am looking for is like this: 我正在寻找的输出是这样的:

{2:4, 10:20,30:60,50:100, 100:200}

What's the mistake I am doing? 我在做什么错?

Thanks. 谢谢。

You can't use an expression as a label in an Object literal, it doesn't get evaluated. 您不能在对象文字中使用表达式作为标签,它不会被求值。 Instead, switch to bracket notation. 而是改用括号表示法。

var original_value = my_arr(Num[i]),
    doubled_value = doubling(Num[i]);
obj = {}; // remove this line if you don't want object to be reset each iteration
obj[original_value] = doubled_value;

Your goal is to enrich the obj map with new properties in order to get {2:4, 10:20,30:60,50:100, 100:200} . 您的目标是使用新属性丰富obj映射,以便获得{2:4, 10:20,30:60,50:100, 100:200} But instead of doing that you're replacing the value of the obj variable with an object having only one property. 但是,与其相反,您将obj变量的值替换为仅具有一个属性的对象。

Change 更改

obj = {original_value : doubled_value};

to

obj[original_value] = doubled_value;

And then, at the end of the loop, just log 然后,在循环结束时,只需登录

console.log(obj);

Here's the complete loop code : 这是完整的循环代码:

for(var i=0; i< Num.length; i++) {
    var original_value = my_arr(Num[i]);
    var doubled_value = doubling(original_value);
    obj[original_value] = doubled_value;
}
console.log(obj);

Or: 要么:

//Original array
var Num=[2,10,30,50,100];
//Object with original array keys with key double values
var obj = myFunc(Num);
//Print object
console.log(obj);


function myFunc(arr)
{
    var obj = {};
    for (var i in arr) obj[arr[i]] = arr[i] * 2;
    return obj;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM