如何防止向数组添加空值?

时间:2016-01-21 18:25:12

标签: javascript arrays

我有一个脚本,它将抛出用户帐户,并将现场手机的价值推入阵列。但是,当移动电话字段为空时,如何防止将数组推入空值?

所以反而是这样的:'123,,,123,123,,123,,123'我希望得到这个:[123,123,123,123,123]

这是检查值是否为空的代码的主要部分:

if (!smsUsers.user.mobile_phone.nil() || 
     smsUsers.user.mobile_phone != null || 
     smsUsers.user.mobile_phone != '' || 
     smsUsers.user.mobile_phone.length != 0 || 
     smsUsers.user.mobile_phone ||
     smsUsers.user.mobile_phone.toString().toLowerCase() != 'false'){

       notSccUserPhone.push(smsUsers.user.mobile_phone);

     }

这就是我现在整个代码的样子:

function getMobileNumber(param) {  
    var sccUserPhone = [];
    var notSccUserPhone = [];                          

    var smsGroup = new CheckServices().getServiceParms("Major Incident", current, true);
    if(smsGroup.next()){
        var smsGroupNumber = smsGroup.u_parm_2;
        gs.log('Group of sms targets ' + smsGroupNumber);

        var smsUsers = new GlideRecord("sys_user_grmember");
        smsUsers.addQuery("group.name", smsGroupNumber);
        smsUsers.query();
        if(param == 'true'){
            while (smsUsers.next()) {
                if(smsUsers.user.email.indexOf('scc') == -1){
                    if (!smsUsers.user.mobile_phone.nil() || smsUsers.user.mobile_phone != null || smsUsers.user.mobile_phone != '' || smsUsers.user.mobile_phone.length != 0 || smsUsers.user.mobile_phone || smsUsers.user.mobile_phone.toString().toLowerCase() != 'false'){
                        notSccUserPhone.push(smsUsers.user.mobile_phone);

                    }
                }       
            }

            gs.log('Not SCC mobile namber array is ' + notSccUserPhone); 
            template.print(notSccUserPhone);
        } else if(param == 'false'){
            while (smsUsers.next()) {
                    if(smsUsers.user.email.indexOf('scc') != -1){
                        if (!smsUsers.user.mobile_phone.nil() || smsUsers.user.mobile_phone != null || smsUsers.user.mobile_phone != '' || smsUsers.user.mobile_phone.length != 0 || smsUsers.user.mobile_phone || smsUsers.user.mobile_phone.toString().toLowerCase() != 'false'){
                            sccUserPhone.push(smsUsers.user.mobile_phone);

                        }

                }
            }

            gs.log('SCC mobile namber array is ' + sccUserPhone);
            template.print(sccUserPhone);
        }
    }

}

1 个答案:

答案 0 :(得分:2)

您可以尝试使用这样的正则表达式:

if (smsUsers.user.mobile_phone != null &&
 smsUsers.user.mobile_phone.match(/\S/) &&
 smsUsers.user.mobile_phone.toString().toLowerCase() != 'false')
{
    notSccUserPhone.push(smsUsers.user.mobile_phone);
}

您还需要将||更改为&&

djechlin pointed out,您没有及早检查null;我把它移到了上面检查的顶部。