Javascript 如何在 jquery 或 js 中创建动态二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10879921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:23:57  来源:igfitidea点击:

How to create dynamic two dimensional array in jquery or js

javascriptjqueryhtmlarraysmultidimensional-array

提问by DEVOPS

I need to create global two dimensional array in jquery or javascript

我需要在 jquery 或 javascript 中创建全局二维数组

My function is like this

我的功能是这样的

<script>

var globalArray[0] = new Array();

function createArray(){

    alert(globalArray[0]);         
}

</script>

<div><input type='button' value='save' onclick='createArray();'> </div>

On click of that button I am getting this error "globalArray[0] is undefined"

单击该按钮时,我收到此错误 "globalArray[0] is undefined"

How can I create global dynamic multi dimensional array.

如何创建全局动态多维数组。

回答by gdoron is supporting Monica

if (!globalArray[index]) 
    globalArray[index] = []; // init the array.

globalArray[index].push(name);

You have a typo with the dot:

你的点有错别字:

$.("#uname").val(); 

Change to:

改成:

$("#uname").val();

What are you trying to do with this code?

你想用这段代码做什么?



Update:(The question was totally edited.)

更新:(问题已完全编辑。)

Your code:

您的代码:

var globalArray[0] = new Array(); 

globalArray[0]is invalid variable name, you need first to declare the array:

globalArray[0]是无效的变量名,你需要先声明数组:

var globalArray = []; // Array literal.
globalArray[0] =  [] // The element at position 0 is new an array. 

回答by Muhammad Raheel

Intead of

代替

if(loop == 0){
 globalArray[index][0] = uname;
}else{
  globalArray[index][loop++] = uname;
}

Use this

用这个

if(loop > 0){
    globalArray[index][loop++] = uname;     
}else{
    globalArray[index][0] = uname;      
}