【问题标题】:How to transfer part of an array to a new line?如何将数组的一部分转移到新行?
【发布时间】:2019-11-14 10:30:54
【问题描述】:

下午好,请告诉我,我有一个由数字组成的数组,如何将数组中每个单元之前的数字后面的部分转移到新的一行?

我的应用程序.vue:

<template>
  <div id="app">
    <div class="mounth">{{ mounthDays }}</div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
        mounthDays: [],
    }
  },
  mounted() {
    for (var x = 0; x < 12; x++) {
      for (var i = 1; i <= 31; i++) {
        this.mounthDays.push(i)
      }
    }
    if(this.mounthDays[123] === 31){
      this.mounthDays.splice(59, 3)
      this.mounthDays.splice(120, 1)
      this.mounthDays.splice(181, 1)
      this.mounthDays.splice(273, 1)
      this.mounthDays.splice(334, 1)



    }
    console.log(this.mounthDays)

    }
  }
</script>

【问题讨论】:

  • 我不确定您要的是什么。你能显示所需的输出吗?
  • 现在我将在我的问题中添加一个屏幕并解释我希望它是怎样的
  • 现在我的数组看起来像这样,我希望数组的其余部分移动到前一个数字之后的新行。
  • 对我来说,真的不清楚你在问什么。您能否重新表述您的问题或展示您想要达到的结果的示例?
  • 比如你看到第二行的数字28,后面是1。这里我要28后面的空行,数组的其余部分转移到新行

标签: javascript arrays loops


【解决方案1】:

不要将所有数字组成一个数组,而是将其设为数组数组,然后将其打印在不同的行上。这样的事情应该可以工作:

var monthsWithDays = [];

for (var x = 0; x < 12; x++) {
    var days = [];

    for (var i = 1; i <= 31; i++) {
        days.push(i)
    }

    monthsWithDays.push(days);
}

monthsWithDays.forEach(daysArray => console.log(daysArray));

如果你只想要一个带有换行符的字符串,那么这样的东西应该可以工作:

monthsWithDays.map(daysArray => daysArray.join(",")).join("\n")

编辑: 我现在看到你想用你的 splice 东西做什么。我认为您在这里没有正确的方法。但是上面的代码可以修复为:

function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}

var monthsWithDays = [];

for (var x = 1; x <= 12; x++) {
    var days = [];

    for (var i = 1; i <= daysInMonth(x, 2019) ; i++) {
        days.push(i)
    }

    monthsWithDays.push(days);
}

monthsWithDays.map(daysArray => daysArray.join(",")).join("\n")

我从another question here借用了daysInMonth函数

【讨论】:

    【解决方案2】:

    这是一个当前年份的工作示例,它使用 computed property 和一些 date math

    <template>
      <div>
        <div v-for="(month, index) in monthsAndDays" :key="index">{{ month }}</div>
      </div>
    </template>
    
    <script>
    // https://stackoverflow.com/questions/1184334
    const daysInMonth = (month, year) => new Date(year, month, 0).getDate();
    
    // [1..n]
    const oneToN = n => Array.from(Array(n), (_, i) => i + 1);
    
    export default {
      computed: {
        monthsAndDays() {
          const year = new Date().getFullYear();
          return oneToN(12).map(i => oneToN(daysInMonth(i, year)));
        },
      },
    };
    </script>
    

    【讨论】:

    • 大声笑,我刚刚引用了同样的 daysInMonth 问题
    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多