简体   繁体   English

将数组连接成字符串

[英]Concatenate array into string

I have this: 我有这个:

var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";

And I want to get the string: 我想获取字符串:

"first":"$firstelement","second": "$secondelement"

How can I do it? 我该怎么做?

What you have is invalid (even if it works) , arrays don't have named keys, but numeric indexes. 您所拥有的是无效的(即使它可以工作) ,数组没有命名键,但是有数字索引。

You should be using an object instead, and if you want a string, you can stringify it as JSON 您应该使用一个对象来代替,如果需要一个字符串,可以将其字符串化为JSON。

 var myobject = {}; myobject["first"] = "$firstelement"; myobject["second"] = "$secondelement"; var str = JSON.stringify(myobject); console.log(str) 

First of all, you'd want to use an object instead of an array: 首先,您想使用一个对象而不是一个数组:

var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";

The easiest way, then, to achieve what you want is to use JSON: 然后,实现所需的最简单的方法是使用JSON:

var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);

JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified. JSON.stringify()方法将JavaScript值转换为JSON字符串,如果指定了replacer函数,则可以选择替换值,如果指定了replacer数组,则可以仅包括指定的属性。

 var myarray = {}; myarray ["first"] = "$firstelement"; myarray ["second"] = "$secondelement"; console.log(JSON.stringify(myarray)); 

使用JSON.strinify()

JSON.stringify(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM