基本上,我有一个多维数组,我需要构建一个简单的字符串。
相当简单的问题,虽然它已经在我身上吃了很长时间了,因为我似乎无法指出它。
以下是一个示例,说明我的数组在其中只有3个问题的外观:
[["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]]
例如,D.rows[0][0]
将是“问题1”而D.rows[2][3]
将是“answer3”,只是为了澄清。
以下是必须如何将其保存为字符串:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
每个元素之间必须有逗号,每个问题必须用换行符分隔。
这是我目前无法正常工作的内容:
var fullString;
for (i = 0; i < csvArray.length; ++i)
{
second = secondArray[i];
for (j = 0; j < second.length; ++j)
{
fullString += entry[j] + "'";
}
fullString += "\n";
}
提前致谢!
答案 0 :(得分:1)
试试这个
var s,a=[["question1","answer1","answer2","answer3","answer4"],"question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
for(i=0; i < a.length; i++){
s=(s)?s+"\n\r"+a[i].join():a[i].join();
}
在您自己的示例中:由于您要直接添加到fullString
,因此它应该有一个空字符串作为值,否则您最终会得到undefined
。
var fullString="";
此部分second = secondArray[i];
应该是
var second = csvArray[i];
并且以同样的方式fullString += entry[j] + "'";
应该是
fullString += second[j] + ",";
答案 1 :(得分:1)
一个班轮:
var result = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]].join('\r\n');
答案 2 :(得分:0)
类似的东西:
var questionAnswerSet = {“question1”:[
{“answer1”:“价值”,
“answer2”:“价值”,
“answer3”:值}
],
“问题2”:[
{“answer1”:“价值”,
“answer2”:“价值”,
“answer3”:值}
]
}
并像这样访问:
questionAnswerSet [0] .answer2 //提问一个答案2
questionAnswerSet [1] .answer2 //提问2答案2
答案 3 :(得分:0)
如果您有一个数组......
var arr = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
...然后
var strArr = arr.join(',');
var strLine = arr.join('\n'); // string with line breaks.
会为你做到这一点。
如果你想为每个问题 - 答案块设置不同的字符串,那么......
var strJoinArr = [], strJoinLines = '';
for(var i = 0; i < arr.length; i++){
strJoinArr.push(arr[i].join(','));
strJoinLines += arr[i].join(',')+ '\n'; // string with line break
}
然后访问每个部分,你可以使用索引,
例如,strJoinArr[2]
将返回'question3,answer1,answer2,answer3,answer4'
答案 4 :(得分:0)
for (var i=0; i<yourArray.length; i++) { // iterate on the array
var obj = yourArray[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}
答案 5 :(得分:0)
如果您计划更改分隔符以获得答案数,这可能是您的解决方案。
var array = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]],
string = "";
for (var i = 0; i <= array.length - 1; i++) {
string +=array[i].join(', ');
string += "\n";
}
此外,对于此结构的任何对象,其可读性较低但也是有效的
string = array.join('\r\n');