js把 ["1", "2", "3"]里面字符串转换成数字类型
时间: 2023-09-10 10:13:22 浏览: 51
可以使用`map()`方法和`parseInt()`函数将数组中的字符串转换为数字类型:
```javascript
const arr = ["1", "2", "3"];
const newArr = arr.map(num => parseInt(num)); // [1, 2, 3]
```
在`map()`方法中,我们使用`parseInt()`函数将每个字符串转换为数字类型。如果字符串中包含非数字字符,则`parseInt()`函数会返回NaN。如果数组中的字符串都是纯数字,那么这个方法将完美地将其转换为数字类型。
相关问题
js里面用+号把字符串类型强转为整数的原理
您好,关于将字符串类型强转为整数的原理,可以通过使用 parseInt() 函数来实现。该函数会将字符串中的数字部分转换为整数,并返回转换后的结果。如果字符串中包含非数字字符,则会忽略这些字符。如果字符串以非数字字符开头,则返回 NaN。
js 对象里面的key从字符串类型变回原来
如果您想将字符串类型的键转换回原来的类型,需要知道原来的类型是什么。以下是几个示例:
1. 将数字字符串键转换回数字类型:
```
let obj = { '1': 'one', '2': 'two', '3': 'three' };
let newObj = {};
for (let key in obj) {
let newKey = isNaN(Number(key)) ? key : Number(key);
newObj[newKey] = obj[key];
}
```
这将创建一个新的对象,其中所有数字字符串键都转换回数字类型。
2. 将日期字符串键转换回日期类型:
```
let obj = { '2022-01-01': 'New Year', '2022-02-14': 'Valentine\'s Day' };
let newObj = {};
for (let key in obj) {
let newKey = isNaN(Date.parse(key)) ? key : new Date(key);
newObj[newKey] = obj[key];
}
```
这将创建一个新的对象,其中所有日期字符串键都转换回日期类型。
请注意,这些示例假设您知道原始键的类型。如果您不知道,那么转换回原始类型可能会更加困难。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)