Aaron
Aaron

Reputation: 2500

Better Way of Creating Many Arrays?

I'm not even sure if this is bad practice or not and needs changing, but want to make sure. It doesn't seem to impact performance at all.

I have a plugin that has many options. The user can enter options in the following format:

speed: "in,out > in,out > in,out"

Each group of "in,out" settings applies to an HTML element being animated - separated by the ">". The above is setting the animation on/off speed for 3 different objects. Everything works perfectly across all browsers now, but I've had to create a ton of arrays to handle all of the settings. Basically there's an array that holds all of the speed_in settings (object1, object2, object3), speed_out, effect_in, etc...

Basically, I have a block of code that is nothing but creating arrays for these sets, like so:

var speed_in_set = [], speed_out_set = [], effect_in_set = [], effect_out_set = [] ....

The array names are based off of the original default setting names:

speed: ... effect: ...

My best guess to make this more efficient is to iterate over the defaults key names and append _on_set and _off_set to create a new array for each one, but have no idea how to do that and if I even need to worry about have too many arrays. Thanks!

Upvotes: 0

Views: 133

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

JSON is an excellent technique for complex array structures, particularly for value/name pairs. Widely used and fast.

EDIT: example.

You can add more properties by adding more elements, instead of creating a new array. Do some searched on JSON on this site and you'll fine some interesting examples. I have one dataset called "data", but you can add others for other purposes, all in on JSON object. It's really like having a small database.

<script type='text/javascript'>
var myData = {"data":[
     {'speed_in_set':10,'speed_out_set':5,'effect_in_set':15,'effect_out_set':200.1},
     {'speed_in_set':15,'speed_out_set':5,'effect_in_set':15,'effect_out_set':200.1, 'color':'red'}
     ]
}    

alert(myData.data[0].speed_in_set)
alert(myData.data[1].speed_in_set) 
alert(myData.data[1].color)   
</script>

Upvotes: 2

Related Questions