javascript 如何将关联数组加入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10659418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:35:48  来源:igfitidea点击:

How to join an associative array into a string

javascriptstringjoinassociative-array

提问by ali

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!

如果我们用“,”字符加入它们 有什么想法吗?谢谢!

采纳答案by Hidde

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

回答by alex

Object.keys(AssocArray).map(function(x){return AssocArray[x];}).join(',');

PS: there is Object.valuesmethod somewhere, but it's not a standard. And there are also external libraries like hashish.

PS:Object.values某处有方法,但它不是标准。还有像hashish.

回答by MaxArt

The implementation of functions like Object.map, Object.forEachand so on is still being discussed. For now, you can stick with something like this:

诸如Object.mapObject.forEach等功能的实现仍在讨论中。现在,你可以坚持这样的事情:

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]);instead of incrementing a counter can actually be fasterin most of recent browsers. See comments.

编辑 2:在大多数最近的浏览器中,似乎arr.push(obj[p]);不是增加计数器实际上可以更快。看评论。