在For循环/ If中删除undefined

时间:2017-08-30 03:05:29

标签: javascript google-apps-script google-sheets

我这里有一个示例代码。

function updateMasterfile() {
  //Source Sheet
  var mstfile_sht = mstfile_ss.getActiveSheet();
  var mstfile_lstrow = mstfile_sht.getLastRow();
  var mst_decrnge = 'A2:I' + mstfile_lstrow;
  var mst_rnge = mstfile_sht.getRange(mst_decrnge);
  var mst_data = mst_rnge.getValues();

  //Target Sheet
  var cstmr_sht = cstmr_ss.getSheetByName('Customers');
  var cstmr_lstrow = cstmr_sht.getLastRow();
  var cstmr_decrnge = 'A2:G' + cstmr_lstrow;
  var cstmr_rnge = cstmr_sht.getRange(cstmr_decrnge);
  var cstmr_data = cstmr_rnge.getValues();

  for (var i=0; i < cstmr_data.length; i++){
    var C_SDOCode = cstmr_data[i][0];
    for (var j=0; j < mst_data.length; j++){
      var M_SDOCode = mst_data[j][6];
      var M_RSMCode = mst_data[j][3];
      var M_RSMEmail = mst_data[j][2];
      var M_SDOEmail = mst_data[j][4];
      if(C_SDOCode == M_SDOCode){
        rtrn_rsmcode = M_RSMCode;
        rtrn_rsmemail = M_RSMEmail;
        rtrn_sdoemail = M_SDOEmail;
        }
      }
    cstmr_data[i][4] = rtrn_rsmcode;
    cstmr_data[i][5] = rtrn_rsmemail;
    cstmr_data[i][6] = rtrn_sdoemail;
    cstmr_rnge.setValues(cstmr_data);
  }
  //Browser.msgBox('Update Completed.');
}

此代码工作正常但是在条件部分时值为false我的意思是如果条件不符合值显示undefined我该如何删除它?或者将其改为空字符串?

1 个答案:

答案 0 :(得分:2)

也许这对你有用。

function updateMasterfile() 
{
  //Source Sheet
  var mstfile_sht = mstfile_ss.getActiveSheet();
  var mstfile_lstrow = mstfile_sht.getLastRow();
  var mst_decrnge = 'A2:I' + mstfile_lstrow;
  var mst_rnge = mstfile_sht.getRange(mst_decrnge);
  var mst_data = mst_rnge.getValues();

  //Target Sheet
  var cstmr_sht = cstmr_ss.getSheetByName('Customers');
  var cstmr_lstrow = cstmr_sht.getLastRow();
  var cstmr_decrnge = 'A2:G' + cstmr_lstrow;
  var cstmr_rnge = cstmr_sht.getRange(cstmr_decrnge);
  var cstmr_data = cstmr_rnge.getValues();

  for (var i=0; i < cstmr_data.length; i++)
  {
    var C_SDOCode = cstmr_data[i][0];
    for (var j=0; j < mst_data.length; j++)
    {
      var M_SDOCode = mst_data[j][6];
      var M_RSMCode = mst_data[j][3];
      var M_RSMEmail = mst_data[j][2];
      var M_SDOEmail = mst_data[j][4];
      if(C_SDOCode == M_SDOCode)
      {
        rtrn_rsmcode = M_RSMCode;
        rtrn_rsmemail = M_RSMEmail;
        rtrn_sdoemail = M_SDOEmail;
       }
    }
    cstmr_data[i][4] = (typeof(rtrn_rsmcode)!='undefined')?rtrn_rsmcode:'';
    cstmr_data[i][5] = (typeof(rtrn_rsmemail)!='undefined')?rtrn_rsmemail:'';
    cstmr_data[i][6] = (typeof(rtrn_sdoemail)!='undefined')?rtrn_sdoemail:'';
    cstmr_rnge.setValues(cstmr_data);
  }
}