我希望使用不同的 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/