Comments (2)
第一感觉结果应该是[ 1, 2, 3 ]
,但答案却是[ 1, NaN, NaN ]
:
['1', '2', '3'].map(parseInt);
// [ 1, NaN, NaN ]
这是因为map()
方法创建一个新数组,该数组中的每个元素都调用一个提供的函数后返回的结果。
parseInt()
方法接收2个参数,第一个参数为要被解析的字符串,第二个参数表示要解析的数字的基数,可选。
map()
有3个参数,分别是当前元素,索引,数组本身,因为parseInt()
方法接收两个参数,所以这里只用到了前两个参数。
详情请看MDN:
因此,['1', '2', '3'].map(parseInt)
的等价代码实际是:
['1', '2', '3'].map((item, index) => {
return parseInt(item, index);
});
执行三次,返回的值依次是:
parseInt('1', 0); // 1
// 基数为0,数字以10进制来解析,返回1
parseInt('2', 1); // NaN
// 基数为1,数字以2进制来解析,但2>1,无法表示,返回NaN
parseInt('3', 2); // NaN
// 基数为2,数字以3进制来解析,但3>2,无法表示,返回NaN
因此,['1', '2', '3'].map(parseInt)
的返回结果当然是[ 1, NaN, NaN ]
了。
如果就想要返回[ 1, 2, 3 ]
,也是可以的,map
里传递Number
即可:
['1', '2', '3'].map(Number);
// [ 1, 2, 3 ]
from blog.
或者给parseInt套一层,扔进map里
function parse(n){
return parseInt(n,10)
}
from blog.
Related Issues (20)
- 当谈及 Web 性能优化时,我们该关注哪些性能指标
- 新一代性能指标 Web Vitals
- position 属性有哪些值,各有什么特点?
- CSS 会阻塞 DOM 解析吗? HOT 1
- px、rpx、em、rem 、vw/vh、百分比的区别?
- 如何解决移动端 Retina 屏 1px 像素问题 ?
- 介绍下 BFC 布局规则,除此之外,你还知道哪些 CSS 格式化上下文?
- 实现元素水平垂直居中的 N 种方式
- CSS 实现多行文本展开收起效果
- CSS 如何画一个实心、带边缘色(气泡聊天框)、圆角的三角形
- N 炫酷的CSS3 loading加载动画,总有一款适合你
- 伪类与伪元素是怎么回事儿?
- 为什么要使用 TypeScript ? TypeScript 相对于 JavaScript 的优势是什么?
- TypeScript 中 const 和 readonly 的区别?枚举和常量枚举的区别?
- TypeScript 中 Interface 与 Type 的区别?在写 TypeScript 的时候,该用哪个比较好?
- TypeScript 中,关于 any 类型,你需要知道的一切
- TypeScript 中 any、unknown、never 和 void 有什么区别? HOT 1
- 盘点 TypeScript 中我们常用的那些神奇符号
- 简易版 useState 实现
- 请问线上版本关闭了吗 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.