Jquery 如何验证select2是否存在错误-无法读取属性';长度';未定义的

Jquery 如何验证select2是否存在错误-无法读取属性';长度';未定义的,jquery,jquery-select2,Jquery,Jquery Select2,我使用的表单有一个select2下拉列表,它的填充方式如下 $('.DropdownPINOption').select2({ placeholder: '-- Select your PIN --', allowClear: true, tags: true, data: data.data.Table }); 当我从另一个数据库迁移数据时,问题出现了。因为我试图在这个下拉列表中填充的值要么为空,要么不是下拉列表中字段中的值 这是我的密码 if

我使用的表单有一个select2下拉列表,它的填充方式如下

 $('.DropdownPINOption').select2({
     placeholder: '-- Select your PIN --',
     allowClear: true,
     tags: true,
     data: data.data.Table
 });
当我从另一个数据库迁移数据时,问题出现了。因为我试图在这个下拉列表中填充的值要么为空,要么不是下拉列表中字段中的值

这是我的密码

 if (data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code != null)
    $("#4txtPin").val(data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code).change();
引发错误:无法读取null的属性“length”

所以我这样做了:

$('#4txtPin option').each(function () {
   if (this.value == data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code) {
       $("#4txtPin").val(data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code).change();
   }
});
它没有显示任何错误,并且按照预期工作。但这感觉不对。select2是否有更好的解决方案?当出现无效值时,如何显示占位符