数组中的索引显示未定义



由于某种原因,当试图从allcontacts数组拼接索引号时,索引号显示为未定义,你知道为什么会发生这种情况吗?非常感谢。

$(document).ready(function() {
let allcontacts = [];
let index = 0;
$(document).on('click', "#addcontact", function() {
let contact = [];
index++;
const eachemail = $(this).closest('#contactdiv').find('#emailinput').not(this).val();
const eachname = $(this).closest('#contactdiv').find('#nameinput').not(this).val();
const eachtype = $(this).closest('#contactdiv').find('#contacttype').not(this).val();
contact.push(eachemail, eachname, eachtype);
allcontacts.push(contact);
});
$(document).on('click', "#removecontact", function() {
allcontacts.splice(index);
$(this).closest('#contactdiv').remove();
});
});

数组中的第一个值有一个索引"0";,因此如果数组为空,则索引为"0"-1〃;。

$(document).ready(function() {
let allcontacts = [];
let index = -1;
});

最新更新