[英]Javascript : Checking if two dimensional array contains element in first dimension
Is there any way to check a two dimensional array's first dimension value existence, so for example 有什么方法可以检查二维数组的一维值是否存在,例如
var groups = [][10];
// so now if "Student" exists in the first dimension I want to increment the second dimension
//if student is already added, increment it
groups["Student"] = groups["Students"] + 1;
// else
groups.push(["Student",0]);
You can do: 你可以做:
if (typeof groups["Student"] != 'undefined') {
groups["Student"] += 1;
}
else {
groups["Student"] = 0;
}
The example you provide seems to be wrong. 您提供的示例似乎是错误的。
Firstly of all a 2D array will be instantiated something like: 首先,将实例化2D数组,例如:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
See: How can I create a two dimensional array in JavaScript? 请参阅: 如何在JavaScript中创建二维数组?
Secondly, you cannot access an array by using keys. 其次,您不能使用键访问数组。 You are just creating properties in your array object. 您只是在数组对象中创建属性。 So: 所以:
groups['Student'] === groups.Student // true
If you go for this approach then, you must consider the following: 如果您采用这种方法,则必须考虑以下几点:
groups['Student'] = undefined; // Your dimension is created
groups.hasOwnProperty('Student'); // true
typeof groups['Student'] == 'undefined' // true
It may be a good idea to consider using only arrays, or just work with objects. 考虑仅使用数组或仅使用对象可能是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.