简体   繁体   中英

generating js objects names and adding values to them

I generate two random arrays and I need to add numbers from them to array which I need to fill with 100 Objects, name them from n1 to n100 and make them look like this:

n1...n100 = {r: realArray[0...100], i: imagArray[0...100])}

Of course I can add them like I did when there were few of them:

var realArray = [],
    imagArray = [];

for (var i=0, t=100; i<t; i++) {
    realArray.push(Math.floor(Math.random() * t) - 50);
    imagArray.push(Math.floor(Math.random() * t) - 50);
}

  var pointsValues = [
  n1 = {r: realArray[0], i: imagArray[0]},
  n2 = {r: realArray[1], i: imagArray[1]},
  n3 = {r: realArray[2], i: imagArray[2]},
  n4 = {r: realArray[3], i: imagArray[3]},
  n5 = {r: realArray[4], i: imagArray[4]},
  n6 = {r: realArray[5], i: imagArray[5]},
  n7 = {r: realArray[6], i: imagArray[6]},
  n8 = {r: realArray[7], i: imagArray[7]},
  n9 = {r: realArray[8], i: imagArray[8]},
  n10 = {r: realArray[9], i: imagArray[9]},
  n11 = {r: realArray[10], i: imagArray[10]},
  n12 = {r: realArray[11], i: imagArray[11]},
  //........................................,
  //........................................,
  //........................................,
  n100 = {r: realArray[100], i: imagArray[100]},
    ];

I know there must be way to do this with a loop, but I can't figure out how to do it, the idea of changing names from n1 to n100 confuses me the most.

you can use pointValues as a object, so you can do the inserts on a for loop, like this:

var pointsValues = {}

for(var j = 0; j<100; j++){
    var index = "n"+(j+1);
    pointsValues[index] = {r: realArray[j], i: imagArray[j]};
}

so you can access the values using pointsValues.n1 or pointsValues['n1'] , and iterate over with with a foreach!

What you're doing with var pointsValues = [ ... n1 = {r: realArray[0], i: imagArray[0]}, is creating a global variable named n1 (at least, if you're not in strict mode). What I think you need is a simple object since array indices can only be numbers while object keys are usually strings. You can access indices of objects using the known bracket notation ( foo['n1'] ). So, a possible solution would be the following:

 var realArray = [], imagArray = []; for (var i=0, t=100; i<t; i++) { realArray.push(Math.floor(Math.random() * t) - 50); imagArray.push(Math.floor(Math.random() * t) - 50); } var result = {}; var len = realArray.length; for (var i = 0; i < len; i++) { result['n' + (i + 1)] = { r: realArray[i], i: imagArray[i], }; } console.log(result); console.log(result['n50']); 

Of course, there are other solutions which may be better suited, but that's dependent on the exact use case.

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