从数组值创建JavaScript对象 [英] Creating javascript object from array values
问题描述
我正在尝试创建一个javascript对象,以便可以将其转换为json字符串,以便通过php更新mysql表.我是Java语言中的对象和json的新手,所以我在网络上关注了一些教程,但似乎仍然无法使它起作用:
I am attempting to create a javascript object so that I can tranfsorm it into a json string in order to update a mysql table via php. I'm new to objects and json in javascript and so I have followed a couple of tutorials on the web but still can't seem to be getting this to work:
var idArray = [ 1, 2, 3];
var slideNo = [ 1, 2, 3];
var isPublished = [ 0, 1, 0];
var floaText = [ 1, 0 , 1];
var myObject = [];
for(var i = 0; i < idArray.length; i++) {
myObject[i] = {
slideId : idArray[i],
slideNo : slideNo [i],
isPublished : isPublished [i],
floatText : floaText [i]
};
}
alert(myObject[0].slideId);
我似乎无法获得上述代码.我还尝试添加如下形式的报价单:
I can't seem to get the above code work. I also tried to add quoation makrs like this:
myObject[i] = {
slideId : "\"" + idArray[i] + "\"",
slideNo : "\"" + slideNo[i] + "\"",
isPublish : "\"" + isPublished[i] + "\"",
floatText : "\"" + floaText[i]
};
但这似乎也不起作用.我在做什么错了?
But that doesn't seem to work either. What am I doing wrong?
推荐答案
看起来像您最近的编辑解决了以下问题之一:您需要在数组周围使用[]
,而不是{}
.
Looks like your recent edit fixed one of the issues: you need []
around your arrays, not {}
.
接下来,您需要更改数组变量名称以匹配您在for循环中使用的名称.
Next, you need to change your array variable names to match what you're using in your for loop.
最后,myObject可能应该是数组,而不是对象,因此将其{}
更改为[]
.
Finally, myObject should probably be an array, not an object, so change its {}
to []
.
这是您代码的更新版本:
Here's an updated version of your code:
var idArray = [ 1, 2, 3];
var slideArray = [ 1, 2, 3];
var publishArray = [ 0, 1, 0];
var floatArray = [ 1, 0 , 1];
var myObject = [];
for(var i = 0; i < idArray.length; i++) {
myObject[i] = {
slideId : idArray[i],
slideNo : slideArray[i],
isPublished : publishArray[i],
floatText : floatArray[i]
};
}
alert(myObject[0].slideId);
这篇关于从数组值创建JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!