【问题标题】:javascript multidimensional array acting strangelyjavascript多维数组行为奇怪
【发布时间】:2015-03-18 16:37:11
【问题描述】:

我正在尝试根据用户在前一个字段中的输入设置 jquery 自动完成输入。

我有一个 php 脚本,它向这个 jquery post 函数返回一个 json 变量。但是之后我似乎无法正确设置我的阵列。

我尝试只为数据设置一个变量并在 $.post 函数之外处理数组,但仍然没有运气。

我只是不确定当“父”值显示为 null 时,我的数组的子值如何以及为什么会正确发出警报?

function populateMetrics(light_id){
    var availableMetrics = [];
    $.post( 
            "getLightMetrics.php",
            { 
              light_id: light_id,
            },
            function(data) {
                $.each(data, function(index, item){
                    alert(index); //correct index
                    availableMetrics[index] = [];
                    availableMetrics[index]['value'] = item.benchmark_id;
                    alert(availableMetrics[index]['value']); //correct value
                    alert(availableMetrics[index]); //null?
                    availableMetrics[index]['label'] = item.benchmark_variant + "-" + item.benchmark_metric;
                    alert(availableMetrics[index]['label']); //correct
                    alert(item.benchmark_id + " = " + item.benchmark_variant + "-" + item.benchmark_metric);
                    alert(availableMetrics[index]); //still null
                });
                alert(availableMetrics); //all null, but correct amount
                $( "#metric" ).autocomplete({
                    source: availableMetrics,
                    focus: function( event, ui ) {
                        $( "#metric" ).val( ui.item.label );
                        return false;
                    },
                    select: function( event, ui ) {
                        $( "#metric" ).val( ui.item.label );
                        $( "#metric_id" ).val( ui.item.value );
                        return false;
                    }
                });
            },
            "json"

    );
}

【问题讨论】:

  • 仅供参考,不要使用警报来调试代码,请使用您的控制台。但你的意思是:alert(availableMetrics[index]); 显示nullnull和空值是有区别的,只是说

标签: javascript jquery json post multidimensional-array


【解决方案1】:

JavaScript 中的多维数组只能有基于整数的索引。它们不像 PHP 中的关联数组那样工作。

您要查找的代码可能是

var availableMetrics = [];

$.each(data, function(index, item) {
    availableMetrics[index] = {
        value: item.benchmark_id,
        label: item.benchmark_variant + "-" + item.benchmark_metric
    };
});

这将创建一个具有valuelabel 属性的对象数组。然后,您将能够使用以下任何一种表示法从数组中检索值:

availableMetrics[index]['value'];
availableMetrics[index].value;

【讨论】:

  • 工作得很好,但是我使用了我在页面的另一部分显示的相同技术。它有效,但它不在 $.post 函数中
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2023-03-27
  • 2012-01-27
  • 2023-03-09
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多