在NodeJS中将数组转换为string

我想在NodeJS中将数组转换为string。

var aa = new Array(); aa['a'] = 'aaa'; aa['b'] = 'bbb'; console.log(aa.toString()); 

但它不起作用。
任何人都知道如何转换?

你正在使用一个像“关联数组”的数组,这在JavaScript中不存在。 改用Object{} )。

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

ab这样a属性不会使用这种方法,因为它们不在数字索引中。 (即arrays的“身体”)

在JavaScript中,Arrayinheritance自Object ,所以您可以像添加其他对象一样添加和删除属性。 所以对于一个数组来说,编号的属性(它们在技术上只是string内的string)在.toString() .join()等方法中是非常重要的。您的其他属性仍然存在并且非常容易访问。 🙂

阅读Mozilla的文档 ,了解有关arrays的更多信息。

 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(",") 

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

 > a = [1,2,3] [ 1, 2, 3 ] > a.toString() '1,2,3' 

另外,如果你想使用string作为键,那么你应该考虑使用一个Object而不是Array ,并使用JSON.stringify来返回一个string。

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

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

 console.log(aa.toString()); 

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

 console.log(aa.join(' and ')); 

在节点中,你可以说

 console.log(aa) 

它会按照它的格式进行格式化。

如果你需要使用结果string,你应该使用

 JSON.stringify(aa)