Javascript:检查二维数组是否包含第一维中的元素

时间:2022-05-28 21:33:56

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]);

2 个解决方案

#1


0  

You can do:

你可以做:

  if (typeof groups["Student"] != 'undefined') {
       groups["Student"] += 1;
  }
  else {
       groups["Student"] = 0;
  }

#2


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.

考虑仅使用数组或仅使用对象可能是个好主意。

#1


0  

You can do:

你可以做:

  if (typeof groups["Student"] != 'undefined') {
       groups["Student"] += 1;
  }
  else {
       groups["Student"] = 0;
  }

#2


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.

考虑仅使用数组或仅使用对象可能是个好主意。