[英]How to most efficiently generate string from array of objects in javascript?
I have the following: 我有以下内容:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]
I want to generate a string like this: "Jordan,6|Jake,7|Mark,10" 我想生成一个这样的字符串:“Jordan,6 | Jake,7 | Mark,10”
What is the most efficient way to do this? 最有效的方法是什么?
I am currently using: 我目前正在使用:
var studentstr = "";
for(var i = 0; i < students.length; i++) {
studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? 另外,性能方面,如果我有2000个项目的数组,那么执行这种转换是“代价高昂”吗? The resulting string contains both keys in the object and not a single join on one object in the property. 结果字符串包含对象中的两个键,而不包含属性中一个对象上的单个连接。
You can map each student object to a string and then join them all with |
您可以将每个学生对象映射到一个字符串,然后使用|
将它们全部连接起来 : :
var studentstr = students.map(function (student) {
return student.name + ',' + student.age;
}).join('|');
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? 另外,性能方面,如果我有2000个项目的数组,那么执行这种转换是“代价高昂”吗?
No. 没有。
Yes, using string concatenation in a loop is costly. 是的,在循环中使用字符串连接是昂贵的。 The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. 每次迭代时字符串都会增长,每次必须复制整个前一个字符串以创建新版本。 The execution time of the loop grows exponentially to the number of items. 循环的执行时间呈指数增长到项目数。
You can put the string for each object in an array, then join them together: 您可以将每个对象的字符串放在一个数组中,然后将它们连接在一起:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]; var items = []; for (var i = 0; i < students.length; i++) { items.push(students[i].name + ',' +students[i].age); } var str = items.join('|'); // display result in snippet document.write(str);
Try this and see your console: 试试这个,看看你的控制台:
var string = '';
for (var s in students) {
string += students[s].name + ', ' + students[s].age + ' | ';
}
console.log(string);
Fiddle: http://jsfiddle.net/80ss0u14/ 小提琴: http : //jsfiddle.net/80ss0u14/
I do not think it is costly to go on with such approach. 我认为采用这种方法并不昂贵。 It may be the most efficient way to iterate through the data. 它可能是迭代数据的最有效方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.