【问题标题】:Use variable to access array results in undefined [duplicate]使用变量访问数组结果未定义[重复]
【发布时间】:2017-10-24 14:44:09
【问题描述】:

我从GET 响应中返回了几个数组,我需要访问这些数组。由于它们的名称可以根据请求更改,因此我有一个变量来指定要使用的数组。

但是我总是不确定。看到这个:

            console.log(current); // trips_out_201702
            console.log(theResponse.current); // undefined
            console.log(theResponse.trips_out_201702); // this works

我怎样才能使theResponse.current 工作以返回current 实际代表的内容?为什么我在那里得到未定义?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    当对象中的属性键是变量时,您可以使用方括号表示法来访问该属性。

      console.log(theResponse[current]);
    

    【讨论】:

    • 谢谢,有道理。
    【解决方案2】:

    当使用动态属性访问时你应该这样做

    theResponse[current] 不是 theResponse.current

    【讨论】:

      【解决方案3】:

      您正在尝试使用对象的方式获取数组值。 您应该立即尝试一下variable['keyName'] 祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多