2010-12-03 107 views
0

我想从一个存储在字符串变量proyNombre上的键获取值,但每当我通过常用方法“myAssociativeArray.MyKey”调用它时,它将获取变量'proyNombre'作为键,而不是获取其值并通过它作为一个关键。如何从javascript中的关联数组中获取“动态”值?

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 
    } 

}); 
+0

请注意,JavaScript没有关联数组 - 只是对象。 – alex 2010-12-03 01:58:24

回答

2

尝试:

console.log(myArray[proyNombre]); 

myArray的实际上是在JavaScript中对象。您可以使用object.propertyNameobject['propertyName']访问对象属性。如果你的变量proyNombre包含一个属性的名称(可以),你可以使用第二个表单,就像我上面所做的那样。 object.proyNombre无效 - proyNombre是一个变量。你不能例如做:

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

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

但你可以这样做:

console.log(myObject.test); 
console.log(myObject['test']); 
console.log(myObject[s]); 
+0

每当8分钟为最佳答案计时器让我 – 2010-12-03 02:01:27

1

简单地访问与myArray[proyNombre]值。

+0

谢谢你们两个,我给了第一个答复的最佳答案,你的解决方案的作品。非常感谢。 – 2010-12-03 02:00:48

1

您需要使用您用来设置的值相同的语法:

console.log(myArray[proyNombre]); 
+0

似乎你已经从sje397复制你的答案 – 2010-12-03 02:09:32

1

你这样做是正确的分配:myArray的[proyNombre。您可以使用相同的方法来检索变量。

如果更改:

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

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

你应该得到相同的值(由变量proyNombre代表的键的值)记录的两倍。

确实,Javascript没有关联数组,但是在访问它们的成员时,Javascript中的对象可以像关联数组一样对待。

相关问题