如何调用在 javascript 的数组中创建的对象的函数?
How do you call functions of objects which were created within an array in javascript?
在下面的代码中,TypeError "database[(0 , 0)].returnVal is not a function" 被吐回:
let database = [
[
new DatabaseItem("00", [1, 2, 3, 4], "abcd", ["haiku", "test"]),
new DatabaseItem("01", [], "", [0, 0, 0, 0, 0, 0])
],
[],
[],
[],
[],
[],
[],
[],
[],
[]
];
console.log("01 ID: " + database[0,0].returnVal());
但下面的代码没问题:
validityTest = new DatabaseItem("00", [1, 2, 3, 4], "abcd", ["haiku", "test"]);
console.log("test ID: " + validityTest.returnVal());
除了在数组外声明我的所有变量(这将使数组的用途最小化)之外,有没有办法纠正这个问题。我需要能够调用数组中对象的函数。
database[0,0]
这不是访问 javascript 中的多维数组的正确语法。此代码使用令人困惑的 comma operator,意思是:"evaluate the left 0 and ignore it, then evaluate the right 0 and use it as the index of database"。换句话说,它最终与 database[0]
.
没有什么不同
改为:
database[0][0]
在下面的代码中,TypeError "database[(0 , 0)].returnVal is not a function" 被吐回:
let database = [
[
new DatabaseItem("00", [1, 2, 3, 4], "abcd", ["haiku", "test"]),
new DatabaseItem("01", [], "", [0, 0, 0, 0, 0, 0])
],
[],
[],
[],
[],
[],
[],
[],
[],
[]
];
console.log("01 ID: " + database[0,0].returnVal());
但下面的代码没问题:
validityTest = new DatabaseItem("00", [1, 2, 3, 4], "abcd", ["haiku", "test"]);
console.log("test ID: " + validityTest.returnVal());
除了在数组外声明我的所有变量(这将使数组的用途最小化)之外,有没有办法纠正这个问题。我需要能够调用数组中对象的函数。
database[0,0]
这不是访问 javascript 中的多维数组的正确语法。此代码使用令人困惑的 comma operator,意思是:"evaluate the left 0 and ignore it, then evaluate the right 0 and use it as the index of database"。换句话说,它最终与 database[0]
.
改为:
database[0][0]