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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26624166/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:08:13  来源:igfitidea点击:

convert integer array to string array in javascript

javascriptarrays

提问by gihansalith

I have an array like below,

我有一个像下面这样的数组,

var sphValues = [1,2,3,4,5];

then I need to convert above array like as below one

然后我需要像下面这样转换上面的数组

var sphValues = ["1","2","3","4","5"];

How can i convert? I used this for autocomplete..

我该如何转换?我用它来自动完成..

回答by elclanrs

You can use mapand pass the Stringconstructor as a function, which will turn each number into a string:

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

sphValues.map(String) //=> ['1','2','3','4','5']

This will not mutate sphValues. It will return a new array.

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

回答by Amir Popovich

Use Array.map:

使用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"] 

Edit:
Better to use arr.map(String);as @elclanrs mentioned in the comments.

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

回答by Skiper Skiprovic

just by using array methods

只需使用数组方法

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

回答by Anarion

for(var i = 0; i < sphValues.length; i += 1){
    sphValues[i] = '' + sphValues[i];
}

回答by Rajaprabhu Aravindasamy

Use .map()at this context that is a better move, as well as you can do like the below code this would add more readability to your code,

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

sphValues.map(convertAsString);

function convertAsString(val) {
  return val.toString();
}

回答by Saranga

 var value;
 for (var i = 0; i < data3.sph.length; i++) {
     value = data3.sph[i];
     //sphValues[i] = data3.sph[i];
     var obj = {
         label: value
     };
     sphValues.push(obj);
 }

You can use this method for auto complete. I think your problem will be solved, but it will not convert like you want, it will convert like

您可以使用此方法自动完成。我认为你的问题会得到解决,但它不会像你想要的那样转换,它会像

["label": "val1", "label": "val2"]

回答by Ekansh Rastogi

you can just append a '' to convert it to a string type.

您只需附加一个 '' 即可将其转换为字符串类型。

var sphValues = [1,2,3,4,5];
for(var itr = 0; itr<sphValues.length;itr++){
  sphValues[itr] = '' + sphValues[itr];
}