如何将javascript中的数字数组转换为字符串? [英] How can I convert an array of numbers in javascript to string?
问题描述
就像我有 var arr = [1,2,3,4,5]
,我希望它成为 arr [ 1 , 2, 3, 4, 5]
。我尝试使用:
Like I have var arr = [1,2,3,4,5]
, I want this to become arr["1","2","3","4","5"]
. I tried using:
var x = arr[0].toString(); //outputs "1"
但是当我执行 typeof x $时c $ c>输出数字。
but when I do typeof x
it outputs "number".
如何转换为当我执行 typeof
时输出字符串?
How can I convert this that when I do typeof
it will output "string"?
推荐答案
最优雅的解决方案
arr = arr.map(String);
这适用于 Boolean
和数字
。引用MDN( https://developer.mozilla.org/ zh-CN / docs / Web / JavaScript / Reference / Global_Objects / String )
This works for Boolean
and Number
as well. Quoting MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
字符串文字(用双精度或单精度表示)引号)和在非构造函数上下文中从字符串调用返回的字符串(即,不使用new关键字)是原始字符串。
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
至于VisioNs的答案,这仅适用于支持 Array.prototype.map
As for VisioNs answer, this only works for browser that support Array.prototype.map
这篇关于如何将javascript中的数字数组转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!