Javascript函数和数组问题

标签 javascript jquery multidimensional-array

我试图将一些数据传递给一个函数,该函数使用这些参数作为多维数组的标识符,然后返回硬编码到该数组的值。我不确定我做错了什么,但有些东西正在破坏。

在分配任何数组值之前,我可以弹出一个alert(),但它似乎在那时就消失了。任何帮助表示赞赏。

    // Get Column A's number
var a1 =  Number($('#p-a').attr("numb"));

// Get Column B's number
var b1 =  Number($('#p-b').attr("numb"));

// Get status for column A
var a_status = $('#p-a').attr("status");

// Get status for column A
var b_status = $('#p-b').attr("status");

// If same, status="s" else, status="i"
var status = "";
if(a_status == b_status) { status = "s"; }else{ status = "o"; }

// Get the value of the numbers + status
var a = this_function(a1, b1, status, "2");

// Update the status div
$('#status').html(a);

function this_function(a1, a2, s, p)
{
    this_array = array();
    this_array['1']['1']['1']['1'] = "10";
    this_array['1']['1']['1']['2'] = "20";
    this_array['1']['2']['1']['1'] = "40";
    this_array['1']['2']['1']['2'] = "60";
    // 
    return this_array[a1][a2][s][p];
}

最佳答案

你不能像这样初始化数组。每个级别都需要单独初始化。由于您没有只有数字键,所以我会使用 object相反:

var this_array = {
    '1': {
        '1': {
            'o': {
              '1': "10",
              '2': "20"
            }
        },
        '2': {
            'o': {
              '1': "40",
              '2': "60"
            }
        }
    }
};

您还必须定义如果 key 不存在会发生什么情况。例如。目前,如果 status's' 那么您将收到错误。

<小时/>

使用 conditional operator 可以将 if 语句写得更短。 :

var status = (a_status == b_status) ? 's' : 'o';
<小时/>

更新:如果您确实想要一个数字数组,只要键只是数字,您可以像这样创建数组:

var this_array = [
    [],                        // this_array[0]
    [                          // this_array[1]
        [],                    // this_array[1][0]
        [                      // this_array[1][1]
            [],                // this_array[1][1][0]
            [null, 10, 20]     // this_array[1][1][1][...]
        ],
        [                      // this_array[1][2]
            [],                // this_array[1][2][0]
            [null, 40, 60]     // this_array[1][2][1][...]                 
        ]
    ]
];

你看,如果你不以 0 开始索引,结构就会变得非常困惑。

关于Javascript函数和数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4741843/

相关文章:

c - 如何在一个函数中动态分配二维数组并在另一个函数中打印它?

javascript - 移动设备上的滚动错误

javascript - 改变圆圈的渐变颜色?

javascript - 如何转义 JSON 字符串以将其包含在 URL 中?

jQuery.submit 从 3.3 开始已被弃用,替代方案是什么?

c# - 如何将二维字符串数组转换为二维 [int, double, bool, ..] 数组?

javascript - 使用 React 的 useCallback hook 代替 useEffect 的目的是什么?

javascript - 在 body 上执行 DOM 操作时,DOMNodeInserted 表现得很奇怪

jquery Draggable +sortable 与自定义 html 的放置事件?

java - Java中数组初始值设定项中带有尾随逗号的数组