arrays - Can a method of an object store the name of the object itself to be recovered as a string in JavaScript? -


if have:

x=3; firstnames = ["john","paul","george","ringo"]; lastnames = ["smith","jonson","jones","doe"]; semirandomnumbers= [3,6,7,4,2,1,0,9]; 

i can set: arraytouse = firstnames; alert(arraytouse[x]); // > "ringo"

i know it's weird, it's how set up. problem lies in:

arraytouse not = firstnames, = "john","paul","george","ringo"

i want to: alert( "the array used was: " +arraytouse+ "." ); , want result be:

"the array used was: firstnames."

i don't want result:

"the array used was: john","paul","george","ringo."

so...... know sounds silly, but, there predefined property of object contains name of object?

i.e. arraytouse.name -> firstnames. ??? (currently undefined)

is there property unaware of use? or, have set on own like: firstnames = ["john","paul","george","ringo"]; firstnames.name="firstnames";

i hate go through trouble/filespace/bandwidth if exists.

before says: "answered elsewhere" admit have seen similar questions, but.. after several hours, keep finding answer work backwards. i.e. poster tells how make new variable name of variable being string contents of array, , poster warns them use existing arrays. exact opposite of looking for/asking.

i want grab name of object/array in string form, not contents of array/object.

the easiest way use object store arrays , variable array property want

x = 3; var arraytousename = "firstnames", arraytouse, data = {   firstnames: ["john", "paul", "george", "ringo"],   lastnames: ["smith", "jonson", "jones", "doe"],   semirandomnumbers: [3, 6, 7, 4, 2, 1, 0, 9] }  arraytouse = data[arraytousename] 

then change array

arraytousename="lastnames"; arraytouse = data[arraytousename]; 

now have access arraytousename.


to same variables have in global namespace , use

window[arraytousename]; 

but putting things in global namespace can create collisions prefer avoid


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -