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.它将返回一个新数组.
用途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)
for(var i = 0; i < sphValues.length; i += 1){
sphValues[i] = '' + sphValues[i];
}
Run Code Online (Sandbox Code Playgroud)
.map()在这种情况下使用这是一个更好的举措,你可以像下面的代码那样做,这将为你的代码增加更多的可读性,
sphValues.map(convertAsString);
function convertAsString(val) {
return val.toString();
}
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
39090 次 |
| 最近记录: |