[英]How to join an associative array into a string
I am trying to do this now and I wonder if there is a "the most used" method to join an associative array (it's values) into a string, delimited by a character. 我现在正试图这样做,我想知道是否有一个“最常用”的方法将一个关联数组(它的值)连接成一个由字符分隔的字符串。
For example, I have 例如,我有
var AssocArray = { id:0, status:false, text:'apple' };
The string resulted from joining the elements of this object will be 连接此对象的元素所产生的字符串将是
"0, false, 'apple'" or "0, 0, 'apple'"
if we join them with a "," character Any idea? 如果我们用“,”字符加入他们任何想法? Thanks!
谢谢!
Object.keys(AssocArray).map(function(x){return AssocArray[x];}).join(',');
PS: there is Object.values
method somewhere, but it's not a standard. PS:某处有
Object.values
方法,但它不是标准。 And there are also external libraries like hashish
. 还有像
hashish
这样的外部库。
Just loop through the array. 只需循环遍历数组。 Any array in JavaScript has indices, even associative arrays:
JavaScript中的任何数组都有索引,甚至是关联数组:
var AssocArray = { id:0, status:false, text:'apple' };
var s = "";
for (var i in AssocArray) {
s += AssocArray[i] + ", ";
}
document.write(s.substring(0, s.length-2));
Will output: 0, false, apple
输出:
0, false, apple
The implementation of functions like Object.map
, Object.forEach
and so on is still being discussed. Object.map
, Object.forEach
等函数的实现仍在讨论中。 For now, you can stick with something like this: 现在,你可以坚持这样的事情:
function objectJoin(obj, sep) {
var arr = [], p, i = 0;
for (p in obj)
arr[i++] = obj[p];
return arr.join(sep);
}
Edit : using a temporary array and joining it instead of string concatenation for performance improvement. 编辑 :使用临时数组并加入它而不是字符串连接以提高性能。
Edit 2 : it seems that arr.push(obj[p]);
编辑2 :似乎是
arr.push(obj[p]);
instead of incrementing a counter can actually be faster in most of recent browsers. 在大多数最近的浏览器中,而不是递增计数器实际上可以更快 。 See comments.
看评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.