[英]Javascript : Checking if two dimensional array contains element in first dimension
有什么方法可以检查二维数组的一维值是否存在,例如
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]);
你可以做:
if (typeof groups["Student"] != 'undefined') {
groups["Student"] += 1;
}
else {
groups["Student"] = 0;
}
您提供的示例似乎是错误的。
首先,将实例化2D数组,例如:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
其次,您不能使用键访问数组。 您只是在数组对象中创建属性。 所以:
groups['Student'] === groups.Student // true
如果您采用这种方法,则必须考虑以下几点:
groups['Student'] = undefined; // Your dimension is created
groups.hasOwnProperty('Student'); // true
typeof groups['Student'] == 'undefined' // true
考虑仅使用数组或仅使用对象可能是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.