在javascript中将整数数组转换为字符串数组

gih*_*ith 62 javascript arrays

我有一个像下面的数组,

var sphValues = [1,2,3,4,5];
Run Code Online (Sandbox Code Playgroud)

然后我需要转换上面的数组,如下所示

var sphValues = ["1","2","3","4","5"];
Run Code Online (Sandbox Code Playgroud)

我怎么转换?我用它来自动完成..

elc*_*nrs 155

您可以使用map并将String构造函数作为函数传递,这会将每个数字转换为字符串:

sphValues.map(String) //=> ['1','2','3','4','5']
Run Code Online (Sandbox Code Playgroud)

这不会改变sphValues.它将返回一个新数组.

  • 我不明白为什么这个没有被接受为答案 (6认同)
  • 对于不支持Array.map的旧浏览器,可以使用underscore.js:_. map(sphValues,String) (3认同)

Ami*_*ich 8

用途Array.map:

var arr = [1,2,3,4,5];
var strArr = arr.map(function(e){return e.toString()});
console.log(strArr); //["1", "2", "3", "4", "5"] 
Run Code Online (Sandbox Code Playgroud)

编辑:
最好arr.map(String);用作评论中提到的@elclanrs.


小智 7

只是通过使用数组方法

var sphValues = [1,2,3,4,5];   // [1,2,3,4,5] 
sphValues.join().split(',')    // ["1", "2", "3", "4", "5"]
Run Code Online (Sandbox Code Playgroud)


Ana*_*ion 6

for(var i = 0; i < sphValues.length; i += 1){
    sphValues[i] = '' + sphValues[i];
}
Run Code Online (Sandbox Code Playgroud)


Raj*_*amy 5

.map()在这种情况下使用这是一个更好的举措,你可以像下面的代码那样做,这将为你的代码增加更多的可读性,

sphValues.map(convertAsString);

function convertAsString(val) {
  return val.toString();
}
Run Code Online (Sandbox Code Playgroud)


xgq*_*rms 5

ES6解决方案

const nums = [1, 2, 3, 4, 5, 10];
// bugfix: the `10` edge case
const strs = Array.from(nums, x => `${x}`);
console.log(strs);
// ['1', '2', '3', '4', '5', '10']
Run Code Online (Sandbox Code Playgroud)

git 差异

-  const strs = Array.from(nums.join(``));
+  const strs = Array.from(nums, x => `${x}`);
Run Code Online (Sandbox Code Playgroud)