简体   繁体   English

通过对象内的索引访问数组

[英]Accessing an array by index within an object

I'm trying to access a particular array by it's index within an object within an object (sorry, this may be the wrong terminology). 我正在尝试通过对象内对象内对象的索引访问特定数组(对不起,这可能是错误的术语)。

var person = {
    name: ["Tom", "Mike", "Sally"],
    hair: {
        style: ["bob", "weave", "mullet"],
        length: ["long","short","medium"]
    }
}

getDetail(length);

function getDetail(det) {
    var answer = person.hair.det[1];
    console.log("Hair " + det + " is " + answer)  //outputs: "Hair length is long"
}

When I do this, I am getting an error of "Can't read property '1' of undefined". 执行此操作时,出现错误“无法读取未定义的属性'1'”。 Which tells me it isn't passing the 'det' variable correctly. 告诉我它没有正确传递'det'变量。 If I take that out and put length instead, it works. 如果我将其取出并放入长度,它将起作用。

What am I missing? 我想念什么?

Thanks! 谢谢!

The problem is that in your case you should be passing a string or a variable to your getDetail() function ( length by itself is none, as it is not defined previously, nor is quoted), also there's the fact that if you want to use a variable to indicate the property/key of an object, you should use this type of syntax: object["property"] . 问题是,在您的情况下,您应该将字符串或变量传递给getDetail()函数( length本身是没有限制,因为以前没有定义,也没有引用),如果您要使用变量表示对象的属性/键时,应使用以下语法: object["property"] You can change your code to: 您可以将代码更改为:

getDetail('length');

function getDetail(det) {
    var answer = person.hair[det][1];
    console.log("Hair " + det + " is " + answer)  //outputs: "Hair length is long"
}

When you say getDetail(length) , that's looking for a variable called length , and passing it into the function. 当您说getDetail(length) ,它正在寻找一个叫做length的变量,并将其传递给函数。 Since it doesn't exist, the function gets undefined . 由于不存在,该函数将undefined

HOWEVER, when you write "myObjectVariableName .etcetera ", it will specifically look for an index called "etcetera" - so it won't even be using your det argument - it's instead looking for the "det" index. 但是,当您编写“ myObjectVariableName .etcetera ”时,它将专门查找名为“ .etcetera ”的索引-因此它甚至不会使用您的det参数-而是在查找“ det”索引。

You can, instead, write either of the following. 您可以改为编写以下任一方法。

myObjectVariableName["myIndexName"]

var myString = "myIndexName";
myObjectVariableName[myString]

Both of those will both have the same result. 两者将具有相同的结果。

So, to get the expected result, what you want to do is pass the string "length" into getDetail, and then replace .det with [det] (darkajax seems to have written what I was going for, but I'm hoping my explanation also helps make sense of why it wasn't working) 因此,要获得预期的结果,你想要做的是把这个字符串“长”到getDetail,然后替换.det[det] (darkajax似乎已经写了什么我去了,但我希望我的解释也有助于弄清为什么它不起作用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM