在分配给数组之前检查可空性

时间:2018-02-22 11:23:45

标签: javascript angular

我定义了多个目标数组并读取多个源数组,并将它们添加到angular 4应用程序中的目标数组中。我需要在将它们添加为错误之前检查是否为空。

目标数组

public remainingCapInsPremiumPaid: number[] = [];
  public remainingCapTaxDeduction: number[] = [];
  public remainingCapLoanToParent: number[] = [];
  public remainingCapContribution: number[] = [];
  public remainingCapDividenedDistribution: number[] = [];
  public remainingCapTerminalValue: number[] = [];
  public remainingCaptNetCost: number[] = [];
  public remainingCommPremiumPaid: number[] = [];
  public remainingCommTaxDeduction: number[] = [];
  public remainingCommNetCost: number[] = [];
  public remainingSelfDiscountedLossesPaid: number[] = [];
  public remainingSelfDiscountedTaxDeduction: number[] = [];
  public remainingSelfNetCost: number[] = [];

阅读来源并分配到目的地

for (let i = 0; i < this.totalYears; i++) {
      // if the years exceed 7 then store the values in the remaining array list to display under the remaining section
      if (i > 6) {


this.remainingCapInsPremiumPaid.push(this.NpvResults.captiveInsPremiumPaid[i]);
    this.remainingCapTaxDeduction.push(this.NpvResults.captiveInsTaxDeduction[i]);
    this.remainingCapLoanToParent.push(this.NpvResults.captiveInsLoanToParent[i]);
    this.remainingCapContribution.push(this.NpvResults.captiveInsCapitalContribution[i]);
    this.remainingCapDividenedDistribution.push(this.NpvResults.captiveDividentDistribution[i]);
    this.remainingCapTerminalValue.push(this.NpvResults.captiveInsTerminalValue[i]);
    this.remainingCaptNetCost.push(this.NpvResults.captiveInsNetCost[i]);
    this.remainingCommPremiumPaid.push(this.NpvResults.captiveInsPremiumPaid[i]);
    this.remainingCommTaxDeduction.push(this.NpvResults.commInsTaxDeduction[i]);
    this.remainingCommNetCost.push(this.NpvResults.commInsNetCost[i]);
    this.remainingSelfDiscountedLossesPaid.push(this.NpvResults.selfInsDiscountedLossesPaid[i]);
    this.remainingSelfDiscountedTaxDeduction.push(this.NpvResults.selfInsDiscountedTaxDeduction[i]);
    this.remainingSelfNetCost.push(this.NpvResults.selfInsNetCost[i]);
  }

2 个答案:

答案 0 :(得分:0)

您必须手动检查每个数组是否为null,

if(this.NpvResults.captiveInsPremiumPai !== null) {
  // write your logic here
}

答案 1 :(得分:0)

在推送任何值之前,您需要检查所有Jenkins Script Console数组是否为可空,如果它们的大小不小于当前索引,请对所有数组进行检查:

source

这样做会检查if(this.NpvResults.sourceArray && this.NpvResults.sourceArray.length>i) this.destinationArray.push(this.NpvResults.sourceArray[i]); 是否不是source array,而null是否不小于索引,因为如果是,那么您将获得length异常