javascript - 为什么数组以字符串形式返回
问题描述
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]
也许问题是如何从单个表单输入字段返回一个数组?
解决方案
这是因为当您输入 [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!
推荐阅读
- angularjs - 使用 2 种方法 POST 和 PUT 发出 js 请求
- asp.net - host https website using IIS across local area network
- eloquent - 在 null 上对成员函数 connection() 的代码接收调用
- c# - 基于 EndTime 属性刷新 WPF ListView
- node.js - How allow my app to POST a cloudfunction in firebase that makes another POST?
- javascript - 在构建时明确导入路径
- ios - 如何通过安装配置文件打印我的应用程序的私人日志
- vue.js - Vue test utils - setChecked() not updating v-model
- php - 从最后循环文件?
- reactjs - 酶:用浅,redux 存储更新不会触发 componentDidUpdate