0

i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.

proyectos.each(function(index){
    var proyNombre = this.value;

    if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
        myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
    }
    else{
        console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
        console.log(myArray.this.value); //doesnt work either
    }

});
1
  • Note that JavaScript doesn't have associative arrays - just objects. Commented Dec 3, 2010 at 1:58

4 Answers 4

2

Try:

console.log(myArray[proyNombre]);

myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:

var myObject = {};
myObject.test = 'test string';

var s = 'test';
console.log(myObject.s); // wrong!!

but you could then do:

console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
Sign up to request clarification or add additional context in comments.

1 Comment

whenever the 8 minutes for best answer timer lets me
2

You need to use the same syntax you used to set the value:

console.log(myArray[proyNombre]);

2 Comments

seems like you have copied your answe from sje397
Nope, just the simplest of Javascript programming questions :)
1

Simply access the value with myArray[proyNombre].

1 Comment

thank you both, i gave the best answer to the fist one replying, both your solutions works. thanks a lot.
1

You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.

If you change:

console.log(myArray.proyNombre);
console.log(myArray.this.value);

to

console.log(myArray[proyNombre]);
console.log(myArray[this.value]);

You should get the same value (the value for the key represented by the variable proyNombre) logged twice.

It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.