我正在尝试创建一个像这样的数组:
Expires
从just:
的数组开始Expires: Sun, 06 Nov 1994 08:49:37 GMT
到目前为止我尝试的所有内容都是无效语法或使初始数组未定义。
答案 0 :(得分:2)
您可能想尝试这样的事情。您将不得不更换硬编码元素......
var fruits = ["Apple", "Banana"];
var tempString = "Pie,Dumpling,Cider";
var tempArray = new Array();
tempArray.push(tempString);
tempString = "Bread,Republic";
tempArray.push(tempString);
var output = {};
for (var i = 0; i < fruits.length; i++)
{
var members = tempArray[i].split(",");
var temp = {};
for(var k = 0; k < members.length; k++)
{
temp[("" + k)] = members[k];
}
output[("" + fruits[i])] = temp;
}
console.log(output);
//Different ways to access the objects
console.log(output.Apple);
console.log(output["Apple"]);
console.log(output.Banana[0]);
console.log(output["Banana"]["0"]);
答案 1 :(得分:2)
这是您将来可能会发现有用的替代方法。
// loop over the fruits
var arr = fruits.reduce(function (fp, fc) {
// get the string (in your example the data-makes value)
// and add each to a new object
var temp = makes[fc].split(', ').reduce(function (p, c, i) {
p[i + 1] = c;
return p;
}, {});
// then concatenate the fruit name and its object to
// the output array
return fp.concat.apply(fp, [fc, temp]);
}, []);
输出
[
"Apple", { "1": "pie", "2": "dumpling", "3": "cider"},
"Banana", { "1": "bread", "2": "Republic" }
]
答案 2 :(得分:1)
试试这个:
var fruits = ["Apple", "Banana"], i, k, members, tmp, output = [];
var final = [];
for (i=0; i < fruits.length; ++i)
{
members = document.getElementById(fruits[i]).getAttribute("data-makes");
tmp = members.split(",");
output[i] = new Object();
for (k=0; k < tmp.length; ++k)
{
output[i][k+1] = tmp[k];
}
final.push(fruits[i])
final.push(output[i])
}
console.log(final);
答案 3 :(得分:1)
首先,请记住JSON键总是字符串 - 没有整数。
["Apple", "Banana"]
// data-makes="Pie,Dumpling,Cider", data-makes="Bread,Republic"
var output = [];
var type;
var fruits = ["Apple", "Banana"];
for (i=0; i < fruits.length; ++i)
{
members = document.getElementById(fruits[i]).getAttribute("data-makes");
tmp = members.split(",");
for (k=0; k < tmp.length; ++k)
{
type = {}
type[fruits[i]] = {}
type[fruits[i]][k] = tmp[k]
output.push(type);
}
}
这将输出:
[
{ "apple" : {
"1" : "pie",
"2" : "Dumpling",
"3" : "Cider"
}
},
{ "banana" : {
"1" : "Bread",
"2" : "Republic"
}
]
不完全是你提出的问题(我无法想象为此使用1-D数组,但你可以明白这一点)
答案 4 :(得分:1)
您的代码中存在两个问题:
首先,您永远不会将{{#autoForm collection="things" id="myForm" }}
{{> afQuickField name='schemaName'}}
{{#afEachArrayItem name="fields"}}
<button type="button" class="btn btn-primary autoform-remove-item"><span class="glyphicon glyphicon-minus"></span></button>
{{> afFieldInput name=this.current.name}}
{{> afFieldInput name=this.current.amount}}
{{/afEachArrayItem}}
<button type="button" class="btn btn-primary autoform-add-item" data-autoform-field="fields"><span class="glyphicon glyphicon-plus"></span></button>
{{/autoForm}}
放在fruits[i]
数组中。
其次,在您首次将output
初始化为数组或对象之前,您无法分配到output[i][k+1]
。
output[i]