简体   繁体   English

Javascript数组无法作为数组访问

[英]Javascript array is not accessible as an array

I'm working with the twitter API and I'm hitting a really confusing issue. 我正在使用twitter API,我遇到了一个非常令人困惑的问题。

I have the following script: 我有以下脚本:

const Twitter = require('twitter-api-stream')
const twitterCredentials = require('./credentials').twitter

const twitterApi = new Twitter(twitterCredentials.consumerKey, twitterCredentials.consumerSecret, function(){
    console.log(arguments)
})

twitterApi.getUsersTweets('everycolorbot', 1, twitterCredentials.accessToken, twitterCredentials.accessTokenSecret, (error, result) => {
    if (error) {
        console.error(error)
    }
    if (result) {
        console.log(result) // outputs an array of json objects
        console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
        console.log(result[0]) // outputs a opening bracket ('[')
        console.log(result[0].text) // outputs undefined
    }
})

Which is calling the following function to interact with twitter: 这是调用以下函数与twitter交互:

TwitterApi.prototype.getUsersTweets = function (screenName, statusCount, userAccessToken, userRefreshToken,cb ) {
    var count = statusCount || 10;
    var screenName = screenName || "";

    _oauth.get(
        "https://api.twitter.com/1.1/statuses/user_timeline.json?count=" + count + "&screen_name=" + screenName
        , userAccessToken
        , userRefreshToken
        , cb
    );
};

It seems like I'm getting the result I want. 好像我得到了我想要的结果。 When I log the result itself I get the following output: 当我记录结果本身时,我得到以下输出:

[
  {
    "created_at": "Thu Sep 01 13:31:23 +0000 2016",
    "id": 771339671632838656,
    "id_str": "771339671632838656",
    "text": "0xe07732",
    "truncated": false,
    ...
  }
]

Which is great, an array of the tweets limited to 1 tweet. 这很棒,推文的数组仅限于1条推文。

The problem I'm running into is when I try to access this array. 我遇到的问题是当我尝试访问这个数组时。

console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
console.log(result[0]) // outputs a opening bracket ('[')
console.log(result[0].text) // outputs undefined

I read back through the api docs for the user_timeline but unless I'm completely missing it I'm not seeing any mention of special output. 我通过api文档回读了user_timeline,但除非我完全错过它,否则我没有看到任何特殊输出。

Any ideas? 有任何想法吗?

Update 更新

Thanks @nicematt for pointing out that answer. 谢谢@nicematt指出答案。

Just to elaborate on the solution, I updated my code to this and now I'm getting the result I want: 只是详细说明解决方案,我更新了我的代码,现在我得到了我想要的结果:

if (result) {
    let tweet = JSON.parse(result)[0] // parses the json and returns the first index
    console.log(tweet.text) // outputs '0xe07732'
}

Thanks for the help! 谢谢您的帮助!

Result is a String and you're indexing it ( result[0] (whereas 0 is converted to a string), is almost identical to result.charAt(0) though), this is why result[0] is equal to "[" –because it's the first character specified in. You forgot to parse the result as JSON data. 结果是一个String ,你正在索引它( result[0] (而0转换为字符串),几乎与result.charAt(0)相同),这就是result[0]等于"["因为它是指定的第一个字符。你忘了将结果解析为JSON数据。

JSON.parse(result).length // probably 1

And result.text is undefined since result (a string) is like an Object (but isn't instanceof) and allow lookups and getters to happen in itself. 并且result.textundefined因为result (一个字符串)就像一个Object (但不是instanceof),并允许查找和getter本身发生。

I'd show the difference between str[0] and str.charAt(0) , too: 我也将显示str[0]str.charAt(0)之间的区别:

str[0] // same as str['0'], but a getter. 0 converts to
       // string (because every key of an object
       // is string in ECMAScript)

str.charAt(0) // get/lookup String#charAt, call it
              // without new `this` context and with arguments list: 0

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

相关问题 通过附加键使Javascript数组元素可访问 - Make Javascript array elements accessible by additional key javascript数组长度无法在网页中访问 - javascript array length not accessible in web page 在 javascript 中命名对象的数组中 - 名称是否可访问? - In an array of named objects in javascript - are the names accessible? Javascript 阵列四个元素,但在控制台中显示并且只能访问三个 - Javascript Array four elements but display in console and accessible only three 如何使数组在Javascript中的不同功能下可访问? - How to make an array accessible under different functions in Javascript? 如何通过JQuery Post传递Javascript数组,以便通过PHP $ _POST数组访问其所有内容? - How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array? 使节点数组在视图中可访问 - Making node array accessible in view 迭代为数组但仍可通过键访问 - Iteration as array but still accessible by a key JavaScript find() 方法搜索对象数组以查找元素,结果不可访问 - JavaScript find() method searches through an array of objects to find an element, the outcome not accessible JS:对象数组可在For循环中访问,而不是在外部 - JS: Object Array accessible in For loop, not out side
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM