Javascript 数组或对象

标签 javascript arrays object

我希望使用不同的 API 调用从各种来源获取内容,并将它们全部整理成具有相同格式的对象或数组。我被 javascript 数组和对象困住了,我发现的所有示例似乎都没有做我想做的事情。这是我要存储的格式。这是我想要实现的示例的伪编码

var content = new Object();
getTweets();
getSoundCloud();
display();


function getTweets() {

    //first result
    content.type = "tweet
    content.text = "the text of the tweet"
    content.image = "the image from the tweet"

    return content;
}

function getSoundCloud() {
    //second result
    content.type = "soundcloud
    content.text = "the name of the song"
    content.image = "the image of the song"

    return content;
}


function display() {
    //for each content
    {
        $("#container").append(content.text);
    }

}

第一个结果由一个函数调用生成,第二个结果由另一个函数调用生成。

我希望这些函数将所有内容一起添加到同一格式对象中。一旦对象被填充,我希望在不同的函数中迭代它并显示在屏幕上。

如何制作这个对象?我试过了,但数据总是一样的,即被相同的值覆盖。在 php 中,这可能是一个关联数组或类似的东西

我想为我拥有的每条内容创建一个对象,并且可以循环遍历它

content[0].type = "tweet"
content[1].type = "coundcloud"

任何带有示例的建议都会很棒。

非常感谢

最佳答案

当你拥有很多东西时,你应该立即思考

I need to store these things in an array.

当您的“事物”复杂并且具有各种属性/状态时,您应该立即思考:

I need to create an object to store them.

... 所以这里最好的是一个对象数组。每个函数都会创建对象并将它们添加到 content,我们将其切换为数组:

var content = []; // Array
getTweets();
getSoundCloud();
display();


function getTweets() {
    var tweet = {}; // This is an object

    tweet.type = "tweet";
    tweet.text = "The text of the tweet";
    tweet.image = "The image of the tweet";

    content.push(tweet); // add the object to the array.
}

function getSoundCloud() {
    var soundcloudThing = {};

    soundcloudThing.type = "soundcloud"
    soundcloudThing.text = "the name of the song"
    soundcloudThing.image = "the image of the song"

    content.push(soundcloudThing);
}

现在要显示这个内容,就像数组一样;此处要做的显而易见的事情是迭代它;

function display() {
    for (var i=0;i<content.length;i++)
    {
        $("#container").append(content[i].text);

        // You can also use content[i].image and content[i].type in here
    }
}

请注意,[]{}literal notation用于创建数组和对象。它的使用优于 new Array()new Object()

关于Javascript 数组或对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799753/

相关文章:

javascript - 移相器 : Key Down + Collision Kill

javascript - 从 VSCode Studio Code Webview API 中的文件夹导入所有文件

java - 在 Java 中创建一副纸牌时出现 ArrayIndexOutOfBoundsException

javascript - 为什么以这种方式交换字符是有效的 JavaScript?

javascript - 如何在javascript中为对象编写原型(prototype)函数?

javascript - 有没有办法使用 getUserMedia 减少延迟?

javascript - 如何选择具有相同 anchor 文本和 href 值的链接

arrays - 在perl中合并数组以创建一个新数组

php - 用数字键替换关联数组键的最快方法

object - “张量”对象没有属性 'assign_add'