简体   繁体   English

二维数组中的访问数据问题

[英]Access data issue in 2D array

I'm using a 2D array to track the occurrence of a value, but I'm having issues manipulating the second-dimension value. 我正在使用2D数组跟踪值的出现,但是在处理第二维值时遇到了问题。 My syntax is definitely off, as I store an integer in the 2D, but cannot get a manipulable integer back. 我的语法绝对不正确,因为我在2D中存储了整数,但无法获取可操作的整数。

var list_elm = [occur1, 0], [occur2, 0] ...;
//stuff that checks for instances
var getNum = list_elm[[list_elm.length - 1][0]]; //last array item's second part
list_elm[[list_elm.length - 1][0]] += 1; //this version produces a string "01111..."
list_elm[[list_elm.length - 1][0]] = getNum++; //this produces NaN

I'm trying to increment: list_elm[...][this one] . 我正在尝试增加: list_elm [...] [this one]

You are accessing the 0 index which is a string.. you need to access the index 1 . 您正在访问0索引,它是一个字符串。.您需要访问索引1 Also you have extra [ ] in the syntax. 另外,语法中还有多余的[ ] To access the 2D array you write something like array[1][0] but what you have is array[[1][0]] which is wrong 要访问2D数组,您需要编写类似于array[1][0]但是您拥有的是array[[1][0]] ,这是错误的

Change syntax to point to index 1 and removing extra braces 更改语法以指向索引1并删除多余的花括号

list_elm[list_elm.length - 1][1] += 1;

var getNum = list_elm[list_elm.length - 1][1];

You have to actually get the numeric char from your string. 您实际上必须从字符串中获取数字字符。 Doing ParseInt directly on your string will give you NAN because the first char can't be converted to a number. 直接在字符串上执行ParseInt将使您得到NAN,因为第一个字符不能转换为数字。

You can avoid the second step if your value is '1occur'. 如果您的值为“ 1occur”,则可以避免第二步。 In this case you can directly parse it as int. 在这种情况下,您可以将其直接解析为int。

 var list_elm = [['occur1', 0], ['occur1', 0]]; var elm = list_elm[list_elm.length-1][0]; // get the string 'occur1' elm = parseInt(elm.substr(elm.length-1)); // get 1 from 'occur1' and covert it to integer. elm++; console.log(elm); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM