在 NodeJS 中将数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8907094/
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
Convert array to string in NodeJS
提问by Magic
I want to convert an array to string in NodeJS.
我想在 NodeJS 中将数组转换为字符串。
var aa = new Array();
aa['a'] = 'aaa';
aa['b'] = 'bbb';
console.log(aa.toString());
But it doesn't work.
Anyone knows how to convert?
但它不起作用。
有谁知道怎么转换?
回答by Dominic Barnes
You're using an Arraylike an "associative array", which does not exist in JavaScript. Use an Object({}) instead.
您正在使用Array类似“关联数组”,它在 JavaScript 中不存在。请改用Object( {})。
If you are going to continue with an array, realize that toString()will join all the numberedproperties together separated by a comma. (the same as .join(",")).
如果您要继续使用数组,请意识到这toString()会将所有编号的属性连接在一起,以逗号分隔。(与 相同.join(","))。
Properties like aand bwill not come up using this method because they are not in the numericindexes. (ie. the "body" of the array)
使用此方法不会出现类似a和b不会出现的属性,因为它们不在数字索引中。(即数组的“主体”)
In JavaScript, Array inherits from Object, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString(), .join(), etc. Your other properties are still there and very much accessible. :)
在 JavaScript 中,Array 继承自Object,因此您可以像添加和删除任何其他对象一样在其上添加和删除属性。因此,对于一个数组中,编号的性质(他们在技术上的引擎盖下是字符串)是什么的方法计数喜欢.toString(),.join()等你的其他属性仍然存在并非常接近。:)
Read Mozilla's documentationfor more information about Arrays.
阅读Mozilla 的文档以获取有关数组的更多信息。
var aa = [];
// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";
// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";
aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")
回答by qiao
toStringis a method, so you should add parenthesis ()to make the function call.
toString是一个方法,所以你应该添加括号()来进行函数调用。
> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Besides, if you want to use strings as keys, then you should consider using a Objectinstead of Array, and use JSON.stringifyto return a string.
此外,如果您想使用字符串作为键,那么您应该考虑使用 aObject代替Array,并且使用JSON.stringify返回一个字符串。
> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
回答by Glenjamin
toString is a function, not a property. You'll want this:
toString 是一个函数,而不是一个属性。你会想要这个:
console.log(aa.toString());
Alternatively, use join to specify the separator (toString() === join(','))
或者,使用 join 指定分隔符 (toString() === join(','))
console.log(aa.join(' and '));
回答by Tor Valamo
In node, you can just say
在节点中,你可以说
console.log(aa)
and it will format it as it should.
它会按照它应该的方式对其进行格式化。
If you need to use the resulting string you should use
如果您需要使用结果字符串,您应该使用
JSON.stringify(aa)

