为什么数组以字符串形式返回

时间:2019-04-25 03:18:39

标签: javascript vue.js mongoose-schema

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

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

猫鼬模式将数据类型定义为数组

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的get请求是

    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)
      });
    },
    },

如果我检查控制台,则输入字段类型是数组

enter image description here

在我单击表格并键入3、50、56、53、3、4后,立即检查控制台是否已更改为字符串

enter image description here

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]

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

3 个答案:

答案 0 :(得分:1)

这是因为当您输入[cit .:]“格式并键入3、50、56、53、3、4时,您给出了它是一个字符串值“。

除非另有说明,否则所有输入数据默认为 strings ,并且必须显式完成!

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

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

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

答案 1 :(得分:0)

尝试对JSON.decode()进行响应

答案 2 :(得分:0)

对于可能会发现此@ window.document和@apple苹果的任何人都有答案-问题是在喂怪之前要在哪里分裂。 .split会这样进入API。现在,在创建时以字符串或数字形式返回数组。

app.post("/api/create", (req, res) => {
  const report = new Report({
    month: req.body.month,
    licenseUsage: {
      chartLabels: req.body.licenseUsage.chartLabels.split(','),
      nyRevit: req.body.licenseUsage.nyRevit.split(',').map(Number)
    }

但是在更新中不能正常工作-错误是.spit不是函数,因为返回的数组不是字符串-但是保存更新时,它会变成字符串。要解决此问题,您必须先添加.toString

app.put("/api/report/update/:id", (req, res) => {
  Report.findByIdAndUpdate(
    req.params.id,
  { $set: 
    {
     licenseUsage: {
          chartLabels: req.body.licenseUsage.chartLabels.toString.split(','),
          nyRevit: req.body.licenseUsage.nyRevit.toString.split(',').map(Number)
        }
相关问题