【问题标题】:Javascript - remove empty or false items from arrayJavascript - 从数组中删除空或错误的项目
【发布时间】:2020-11-26 11:55:32
【问题描述】:

我正在使用服务器上的 php 解码文件。当响应提供给客户端并且我使用v-if 在我的 vue 应用程序中循环它时,我遇到了一个奇怪的行为,它会正确循环所有项目并显示在屏幕上(我是以数据 uri 格式循环图像)但在循环内我将始终得到两个 false 项目,因此在输出中我将有两个空白图像标签。我不确定这是否是由循环数据 URI 引起的,但有没有办法从数组中删除错误项目?

这是客户端代码

      axios.request({
        url: 'https://localhost:3000/api/readfile', 
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${this.$store.getters.userToken}`
        },
        data: formData
      }).then( (response) => {
        console.log(response);
        response.data.master_file.forEach( (item) => {
          console.log(item);
          this.payload.push(item);
        });
        this.step++;
        this.isLoading = false;
      });

【问题讨论】:

  • 到目前为止你尝试过什么?你试过什么吗?
  • 只需将this.payload.push(item) 包裹在 if 语句中并检查项目是否存在
  • @ozgur 不错的解决方案,我没想到。我也可以使用三元运算符来检查项目吗?
  • @newbiedev 我会将其发布为答案,以便您尝试
  • 谢谢,它对所有有这个问题的人都有用。

标签: javascript arrays vue.js


【解决方案1】:

您可以将 Array.push() 包装在 if 语句中以避免添加 false 项。

axios.request({
url: 'https://localhost:3000/api/readfile', 
method: 'GET',
headers: {
  'Authorization': `Bearer ${this.$store.getters.userToken}`
},
data: formData
}).then( (response) => {
    console.log(response);
    response.data.master_file.forEach( (item) => {
      console.log(item);
      if (item) {
        this.payload.push(item);
      }
    });
    this.step++;
    this.isLoading = false;
  });

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2014-05-01
    • 2015-10-25
    • 1970-01-01
    • 2021-10-03
    • 2019-06-28
    • 2020-08-29
    • 2018-06-08
    相关资源
    最近更新 更多