在NodeJS中将数组转换为字符串

Mag*_*gic 21 node.js

我想在NodeJS中将数组转换为字符串.

var aa = new Array();
aa['a'] = 'aaa';
aa['b'] = 'bbb';

console.log(aa.toString());
Run Code Online (Sandbox Code Playgroud)

但它不起作用.
谁知道怎么转换?

Dom*_*nes 32

你正在使用Array类似"关联数组",这在JavaScript中是不存在的.请改用Object({}).

如果您要继续使用数组,请意识到toString()将以逗号分隔的所有编号属性连接在一起.(同.join(",")).

类似于ab不会使用此方法的属性,因为它们不在数字索引中.(即阵列的"体")

在JavaScript中,Array继承自Object,因此您可以像任何其他对象一样在其上添加和删除属性.因此,对于一个数组中,编号的性质(他们在技术上的引擎盖下是字符串)都在类似的方法才算数.toString(),.join()等你的其他属性仍然存在并非常接近.:)

有关阵列的更多信息,请阅读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(",")
Run Code Online (Sandbox Code Playgroud)


qia*_*iao 17

toString是一个方法,所以你应该添加括号()来进行函数调用.

> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Run Code Online (Sandbox Code Playgroud)

此外,如果你想使用字符串作为键,那么你应该考虑使用a Object代替Array,并使用JSON.stringify返回字符串.

> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
Run Code Online (Sandbox Code Playgroud)


Gle*_*min 5

toString是一个函数,而不是一个属性。您会想要这样的:

console.log(aa.toString());
Run Code Online (Sandbox Code Playgroud)

或者,使用join指定分隔符(toString()=== join(','))

console.log(aa.join(' and '));
Run Code Online (Sandbox Code Playgroud)