首页 > 解决方案 > 为什么数组以字符串形式返回

问题描述

create.vue 组件提交一个数组,其中 chartLabels 的 data 属性定义为一个数组。

  data() {
    return {
      report: {
        licenseUsage: {
          chartLabels: [],
}
...

Mongoose Schema 将数据类型定义为数组

const ReportSchema = Schema(
    {
      licenseUsage: {
        chartLabels: Array,
      },

创建报告的 API 是

app.post("/api/create", (req, res) => {
  const report = new Report({
  licenseUsage: {
      chartLabels: req.body.licenseUsage.chartLabels,
}
...
});
  report.save(err => {
    if (err) return res.status(404).send({ message: err.message });

    return res.send({ report });
  });

axios 的获取请求是

    created: function() {
      this.getReport();
  },

    methods: {
    getReport() {
      axios.get("http://127.0.0.1:8000/api/report/" + this.$route.params.id).then(response => {
        this.report = response.data.report
        const { chartLabels } = response.data.report.licenseUsage
        this.chartLabels = chartLabels
        console.log(chartLabels)
      });
    },
    },

如果我检查控制台输入字段类型是一个数组的形式

在此处输入图像描述

一旦我单击表单并键入 3、50、56、53、3、4 检查控制台更改为字符串

在此处输入图像描述

axios 将数据作为数组中的字符串返回

["3, 50, 56, 53, 3, 4", __ob__: Observer]
0: "3, 50, 56, 53, 3, 4"

为什么我得到一个由 1 个字符串组成的数组?我希望得到一个像这样的数组 6 个项目。

Array(6)
0: 3
1: 50
2: 56
3: 53
4: 3
5: 4

谢谢你的帮助

- 编辑

如果数组是硬编码的,而不是像这样定义为空数组,那么它会返回一个包含 6 个项目的数组。

chartLabels: [3, 50, 56, 53, 3, 4]

也许问题是如何从单个表单输入字段返回一个数组?

标签: javascriptvue.jsmongoose-schema

解决方案


这是因为当您输入 [cit.:]“表单并键入 3、50、56、53、3、4”时,您正在一个字符串值。

除非另有说明,否则所有输入数据都默认为字符串,并且必须明确完成!

在早于 HTML 5 的版本中,您只能放置/获取字符串类型的数据。现在,在许多其他新的输入属性中,您可以拥有:<input type="number">,但没有输入类型 =“数组”之类的东西。

因此,您需要输入数据转换为数组对象,然后再将其提供给怪物。最简单的方法是:

"3, 50, 56, 53, 3, 4".split(",");
>> [ 3, 50, 56, 53, 3, 4 ]
//WARNING: each 'number' will be a string of course!

推荐阅读