Javascript对象子参考?

时间:2012-04-29 22:20:22

标签: javascript oop

我有一个javascript对象,我需要引用其中一个孩子的值。孩子应该成为阵列的一部分。

这有效:

this.manager.response.highlighting[doc.id]['sentence_0002']

但这不是:

this.manager.response.highlighting[doc.id][0]

我不知道将返回哪些sentence_000*个数字,所以我想用它的数组编号来引用它。

this.manager.response.highlighting[doc.id].length

也不会返回任何内容。

以下是转换为javascript对象的xml文档的一部分:

<response>
  <lst name="highlighting">
    <lst name="http://www.lemonde.fr/international/">
      <arr name="sentence_0005">
        <str> puni pour sa gestion de la crise Geir Haarde a été condamné pour avoir manqué aux devoirs de sa </str>

我需要访问的是<str>中的值。 doc.id已成功设置为http://www.lemonde.fr/international/

3 个答案:

答案 0 :(得分:0)

如果highlighting[doc.id]的属性名称为sentence_xyz,则该属性的位置顺序,但您可以使用{{{}找出存在的密钥1}}循环:

for..in

您可能会发现需要过滤掉其他属性,您可以使用常用的字符串方法,例如:

var key, val;
var obj = this.manager.response.highlighting[doc.id];
for (key in obj) {
    // Here, `key` will be a string, e.g. "sentence_xyz", and you can get its value
    // using
    val = obj[key];
}

您可能还会发现hasOwnProperty很有用,但我猜这是一个来自JSON文本响应的反序列化对象图,在这种情况下for (key in obj) {[ if (key.substring(0, 9) === "sentence_") { // It's a sentence identifier } } 并没有真正进入它。

答案 1 :(得分:0)

在你的问题中:

  

我有一个javascript对象,我需要引用其中一个孩子的值。孩子应该成为阵列的一部分。

     

这有效:

this.manager.response.highlighting[doc.id]['sentence_0002'] 
     

但这不是:

this.manager.response.highlighting[doc.id][0] 

这表明this.manager.response.highlighting[doc.id]引用的对象具有名为sentence_0002的属性,并且它没有名为“0”的属性。

该对象可能是Object或Array(或任何其他对象,如Function或甚至DOM对象)。请注意,在javascript中,Arrays只是具有特殊长度属性的对象,并且一些方便的继承方法通常可以通常应用于任何对象。

因此,this.manager.response.highlighting[doc.id]引用的对象是一个数组还是一个对象在上面没有区别,因为你所追求的属性似乎有一个普通的对象名,而不是预期的数字索引如果它是一个数组并被用作数组。

答案 2 :(得分:0)

您现在可以找到对象的长度,但索引不是数字,它将是'sentence_000 *'

这样做:

 var obj = this.manager.response.highlighting[doc.id],
     indexes = Object.getOwnPropertyNames(obj),    
     indexLength = indexes.length;
 for(var counter = 0; counter < indexLength; counter++){
    obj[indexes[counter]] == val // obj[indexes[counter]] is same as this.manager.response.highlighting[doc.id]['sentence_000*'] 
 }