Giter VIP home page Giter VIP logo

Comments (2)

lzxjack avatar lzxjack commented on September 17, 2024 1

第一感觉结果应该是[ 1, 2, 3 ],但答案却是[ 1, NaN, NaN ]

['1', '2', '3'].map(parseInt);
// [ 1, NaN, NaN ]

这是因为map()方法创建一个新数组,该数组中的每个元素都调用一个提供的函数后返回的结果

parseInt()方法接收2个参数,第一个参数为要被解析的字符串,第二个参数表示要解析的数字的基数可选

map()3个参数,分别是当前元素索引数组本身,因为parseInt()方法接收两个参数,所以这里只用到了前两个参数。

详情请看MDN:

map()

parseInt()

因此,['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.

sunzehui avatar sunzehui commented on September 17, 2024

或者给parseInt套一层,扔进map里
function parse(n){
return parseInt(n,10)
}

from blog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.