为什么即使在我刚刚推送一个新数组之后,嵌套数组的长度仍返回为未定义?



我开发Slack应用已经有一段时间了。我有一个按钮,根据人的用户ID和名称创建一个提交ID,这将被推到一个数组与从未来模态输入收集的其他一些信息一起。然后将该数组推入另一个数据库数组以跟踪所有提交数组。

我正在尝试构建一个函数来迭代嵌套数组,并检查参数(submissionId)是否已经在嵌套数组中。

当我运行我的代码时,它返回"TypeError: Cannot read property 'length' of undefined.">

在我的代码中,您将看到我在使用if语句检查之前将一个新的子数组推入父数组。为什么它会返回undefined?确实存在子数组来检查。

的长度。
// Function to check if submission ID already exists in DB
function checkDupe(submissionId) {

// Result to track if ID is found or not, view to return the correct view based on result
let result;
let view;
// Push new array for the sake of testing; should always return true in this case
payrollDb.push(new Array(submissionId));
// This logs correctly with the submissionId param
console.log(payrollDb[0][0]);
// Nested for-loop to iterate through subarray values and check for submissionId
for(let i=0; i<payrollDb.length; i++) {
for(let j=0; j<payrollDb[i].length; j++) {
console.log(submissionId,"n", payrollDb[i][j]);
payrollDb[i][j] === submissionId ? result = true : result = false;
}

};
// If found, return the error modal, if not continue with the next modal.
result ? view = views_payroll_duplicate : view = views_payroll_period;
return view;

}
我在这里不知所措。我只想让它检查submissionId是否已经存在于我的数据库中如果有,返回一个JSON主体,如果没有找到重复的,则返回另一个JSON主体。

任何关于如何修复或甚至改善我所拥有的建议将不胜感激!

我打赌其中一个payrollDb[I]是未定义的。这行之后:

for(let i=0; i<payrollDb.length; i++) {

在下一个循环之前添加一个检查来记录[i]。然后,当它出错时,导致问题的位置应该显示出来,并且您应该能够围绕它进行编码。你也可以将第二个for语句包装在一个条件语句中,如果它没有定义就跳过它。

for(let i=0; i<payrollDb.length; i++) {
if ([i] === undefined) { // check the type equals undefined
for(let j=0; j<payrollDb[i].length; j++) {

看来我找到问题了。老实说,我不知道为什么这工作,但它确实。

我在循环之前添加了一个变量,等于我要循环的数组的长度,然后在for循环中使用它,而不是直接调用payrollDb。length or payrollDb[i].length.

更新后的代码如下:

function checkDupe(submissionId) {
let result;
let view;
// Set variable for outer array length
let n = payrollDb.length;
for(let i=0; i<n; i++) {
// Set variable for inner array length
let m = payrollDb[i].length;
for(let j=0; j<m; j++) {
payrollDb[i][j] === submissionId ? result = true : result = false;
}
};
result ? view = views_payroll_duplicate : view = views_payroll_period;
return view;

}

如果有人能进一步解释那就太好了!!

最新更新