javascript多维数组行为异常

格鲁斯顿94

我试图根据用户在上一个字段中的输入来设置一个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"

    );
}
安德烈·迪翁

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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章