4

js 字符串数组和数字数组互转

 2 years ago
source link: https://hellodk.cn/post/139
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

今天使用 FormItem 组件时从 initialValue 中发现 "1,2,3"这样的字符串经过 split 操作后得到的结果是字符串数组。

const str = '1,2,3';
const arr = str.split(',');
console.log('arr', arr);

打印出来的结果是:

(3) ["1", "2", "3"]
0: "1"
1: "2"
2: "3"
length: 3

那么如何把字符串数组转换成 number 数组呢

js 把字符串数组转换成 int 型数组

const strArray = ['1','2','3'];
const intArray = strArray.map(Number);
console.log('intArray', intArray);
const strArray = ['1','2','3'];
const intArray = strArray.map((item) => {
return parseInt(item);
console.log('intArray', intArray);

打印出来的效果是:

intArray
(3) [1, 2, 3]

每一项都变成了数字型。

那反过来

js 把数字数组转换为字符串数组

const intArray = [4, 5, 6];
const StringArray = intArray.map(String);
console.log('StringArray', StringArray);

打印出来的结果是:

StringArray
(3) ["4", "5", "6"]
0: "4"
1: "5"
2: "6"
length: 3

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK