如何在 Jquery 中将键和值推送到数组中
我正在阅读 RSS feed 并将标题和链接推送到 Jquery 中的数组中。
我所做的是
var arr = [];
$.getJSON("displayjson.php",function(data){
$.each(data.news, function(i,news){
var title = news.title;
var link = news.link;
arr.push({title : link});
});
});
我正在使用它再次读取该数组
$('#show').click(function(){
$.each(arr, function(index, value){
alert( index +' : '+value);
});
});
但它给了我输出,如下所示
1:[Object Object]
2:[Object Object]
3:[Object Object]
...
我如何同时获得tile和link 作为一对(标题作为键,链接作为值)
I am reading RSS feed and pushing both Title and Link into an Array in Jquery.
What i did is
var arr = [];
$.getJSON("displayjson.php",function(data){
$.each(data.news, function(i,news){
var title = news.title;
var link = news.link;
arr.push({title : link});
});
});
And i am reading that array again using
$('#show').click(function(){
$.each(arr, function(index, value){
alert( index +' : '+value);
});
});
But it Giving me Output as
1:[Object Object]
2:[Object Object]
3:[Object Object]
like this ...
How i can get both tile and link as a pair ( title as key and link as value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这段代码
并没有按照你想象的那样做。推送的是一个新对象,其中有一个名为“title”的成员,并且以
link
作为值...实际的title
值未使用。要保存具有两个字段的对象,您必须执行类似的操作
,或者使用最近的 Javascript 进步,您可以使用快捷方式
如果您希望对象的键是变量
title
的内容,您可以使用This code
is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with
link
as the value ... the actualtitle
value is not used.To save an object with two fields you have to do something like
or with recent Javascript advances you can use the shortcut
If instead you want the key of the object to be the content of the variable
title
you can use我认为你需要定义一个对象,然后推入数组
I think you need to define an object and then push in array
您不是推入数组,而是将键
title
的元素设置为值link
。因此你的数组应该是一个对象。You're not pushing into the array, you're setting the element with the key
title
to the valuelink
. As such your array should be an object.您的意思可能是这样的:
您可以为对象设置一个枚举,例如:
({})[0] = 'txt';
,并且您可以为数组设置一个键,例如:([ ])['myKey'] = 'myVal';
希望这有帮助:)
You might mean this:
You can set an enumerable for an Object like:
({})[0] = 'txt';
and you can set a key for an Array like:([])['myKey'] = 'myVal';
Hope this helps :)
JavaScript 数组中没有键。为此目的使用对象。
在 JavaScript 中,对象扮演关联数组的角色。请注意,对象在迭代时没有定义的“排序顺序”(见下文)。
但是,就您而言,我根本不清楚为什么要从原始对象(
data.news
)传输数据。为什么不简单地传递对那个对象的引用?您可以组合对象和数组来实现可预测的迭代和键/值行为:
There are no keys in JavaScript arrays. Use objects for that purpose.
In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).
However, In your case it is not really clear to me why you transfer data from the original object (
data.news
) at all. Why do you not simply pass a reference to that object around?You can combine objects and arrays to achieve predictable iteration and key/value behavior: