如何将数组的一部分转移到新行?

时间:2019-07-03 17:13:30

标签: javascript arrays loops

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

我的App.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>

enter image description here

That's how I want my array to look

2 个答案:

答案 0 :(得分:0)

不是由所有数字组成的数组,而是使其成为数组的数组,然后将其打印在单独的行上。这样的事情应该起作用:

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功能

答案 1 :(得分:0)

这是当年的工作示例,它使用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>