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
convert integer array to string array in javascript
提问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
回答by Amir Popovich
回答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];
}

