我正在阅读RSS feed篇文章,并将标题和链接放入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});
                });                      
            });

我正在使用以下命令再次读取该数组

$('#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 ...

如何将tilelink作为一对(title as key and link as value)

推荐答案

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

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:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});

Jquery相关问答推荐

Django BaseDataTableView-Filter_queryset方法不起作用

我在自定义 WordPress 插件中使用 ajax 时收到错误请求

如何在外部JS文件中使用带有参数的laravel路由

jQuery 与 ExtJS

jQuery 中的 $this 与 $(this)

Backbone.js 和 jQuery

按百分比zoom div的内容?

JavaScript / jQuery:测试窗口是否有焦点

禁用 Android 网页中输入焦点的zoom

试图检测浏览器关闭事件

你如何获得文本区域中的光标位置?

jQuery - 使用发布数据重定向

自动完成将值而不是标签应用于文本框

如何清除/重置 jQuery UI Datepicker 日历上的选定日期?

Isotope 和 Masonry jQuery 插件之间的区别

jQuery位置href

IE8 和 JQuery 的 trim()

Twitter Bootstrap 中的树

在 Javascript/jQuery 中,(e) 是什么意思?

清除表jquery