【问题标题】:Change the index of an array in array push在数组推送中更改数组的索引
【发布时间】:2021-09-21 04:38:06
【问题描述】:

在应用程序中,我们实现了 laravel-vue-pagination,在我们的分页中,我们的列是复选框和支付金额(输入字段),其中复选框是用户想要支付的项目。

页面加载后,会保存在一个名为 items 的变量中。

我们有一个点击复选框的事件,当用户选中它时,它将推送到另一个名为 selected_items 的变量。当它被取消选中时,它将删除 selected_items 中的值

getPerSelectedItems(i,purchase_item_id){
  if(this.items.data[i].checked == true)
  {
    this.selected_items.push({
      amount_due: this.items.data[i].amount_due,
      balance: this.items.data[i].balance,
      checked: this.items.data[i].checked,
      date_due: this.items.data[i].date_due,
      net_of_vat: this.items.data[i].net_of_vat,
      number: this.items.data[i].number,
      paid_amount: this.items.data[i].paid_amount,
      purchase_item_id: this.items.data[i].purchase_item_id,
      purchase_tag: this.items.data[i].purchase_tag,
      selected_chart_of_account: { id: this.items.data[i].selected_chart_of_account.id, name: this.items.data[i].selected_chart_of_account.code+" : "+this.items.data[i].selected_chart_of_account.name },
      selected_responsibility_center: { id: this.items.data[i].selected_responsibility_center.id, name: this.items.data[i].selected_responsibility_center.name },
      selected_wht_list: { id: this.items.data[i].selected_wht_list.id, name: this.items.data[i].selected_wht_list.name, rate: this.items.data[i].selected_wht_list.rate },
      total_amount_payable: this.items.data[i].total_amount_payable,
      total_wht: this.items.data[i].total_wht,
      transaction: this.items.data[i].transaction,
      transaction_id: this.items.data[i].transaction_id,
      wht_payable: this.items.data[i].wht_payable,
      with_tax: this.items.data[i].with_tax
    })
  }else{
    this.selected_items = this.selected_items.filter(function( obj ) {
        // return obj.purchase_item_id !== this.items.data[i].purchase_item_id;
        return obj.purchase_item_id !== purchase_item_id;
    });
  }
},

例如我检查了这两个项目,变量项目会是这样的。

下面是选定的项目。

现在我的问题是可以更改 selected_items 的索引吗?在我上面的例子中, selected_items 应该是这样的

selected_items: [
   5: {},
   6: {}
]

不是这样的

selected_items: [
       0: {},
       1: {}
    ]

【问题讨论】:

    标签: laravel laravel-vue


    【解决方案1】:

    Javascript 数组不能跳过索引或有“字符串索引”。一个 Javascript 数组是专门用数字索引的。当您设置“字符串索引”时,您正在设置对象的属性。

    如果你设置一个数组的索引 5 和 6,它会是这样的。

    selected_items: [
       0: undefined,
       1: undefined,
       2: undefined,
       3: undefined,
       4: undefined,
       5: {},
       6: {}
    ]
    

    【讨论】:

      【解决方案2】:

      this.selected_items.push() 将始终设置数字键索引。

      您应该使用它来设置特定的索引。

      this.selected_items[i] = this.items.data[i];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        相关资源
        最近更新 更多