为什么['1','7','11']。Map(parseInt)在Javascript中返回[1,NaN,3]?


JavaScript很奇怪。 不信? 好吧,然后尝试使用mapparseInt将字符串数组转换为整数。 启动控制台(Chrome上为F12),粘贴以下代码,然后按Enter


['1', '7', '11'].map(parseInt);

[1, 7, 11] [1, NaN, 3]. ? , Javascript. TL;DR, .



if-else Javascript:


if (true) {
    //  
} else {
    //   
}

, if , else . , true — . ?


if ("hello world") {
    //  ?
    console.log(" ");
} else {
    //  ?
    console.log(" ");
}

. « », «hello world» true.


Javascript true, false. , if-else, true false «». , ? :


, : false, 0, "" ( ), null, undefined, NaN.


, «false», «0», {} [] — . , Boolean  (, Boolean(«0»);).


   , 0 .



0 1 2 3 4 5 6 7 8 9 10

, (0-9). , , (1 0) . , .


— , . , , .


DECIMAL   BINARY    HEXADECIMAL
RADIX=10  RADIX=2   RADIX=16
0         0         0
1         1         1
2         10        2
3         11        3
4         100       4
5         101       5
6         110       6
7         111       7
8         1000      8
9         1001      9
10        1010      A
11        1011      B
12        1100      C
13        1101      D
14        1110      E
15        1111      F
16        10000     10
17        10001     11

, 11 . — 3. — 17.


parseInt 3, 11, .



Javascript , . , ( arguments object).


function foo(x, y) {
    console.log(x);
    console.log(y);
}

foo(1, 2);       //  1, 2
foo(1);           //  1, undefined
foo(1, 2, 3);   //  1, 2

map()


!


Map — , . , 3:


function multiplyBy3(x) {
    return x * 3;
}

const result = [1, 2, 3, 4, 5].map(multiplyBy3);

console.log(result);   //  [3, 6, 9, 12, 15];

, map() ( return). console.log map() … ?


[1, 2, 3, 4, 5].map(console.log);


- . , console.log .


[1, 2, 3, 4, 5].map(console.log);

// :
[1, 2, 3, 4, 5].map(
    (val, index, array) => console.log(val, index, array)
);

//   :
[1, 2, 3, 4, 5].map(
    val => console.log(val)
);

map() : currentValue, currentIndex  array. .


.



ParseInt : string radix (). radix , 10.


parseInt('11');                  => 11
parseInt('11', 2);              => 3
parseInt('11', 16);            => 17

parseInt('11', undefined);  => 11 (radix )
parseInt('11', 0);              => 11 (radix )

.


['1', '7', '11'].map(parseInt);       => [1, NaN, 3]

//  : val = '1', index = 0, array = ['1', '7', '11']

parseInt('1', 0, ['1', '7', '11']);   => 1

0 , — 10. parseInt() , ['1', '7', '11'] . '1' 10 1.


//  : val = '7', index = 1, array = ['1', '7', '11']

parseInt('7', 1, ['1', '7', '11']);   => NaN

1 '7' . , . parseInt() NaN.


//  : val = '11', index = 2, array = ['1', '7', '11']

parseInt('11', 2, ['1', '7', '11']);   => 3

'11' 3. .


(TL;DR)


['1', '7', '11'].map(parseInt) , map parseInt() . index parseInt  radix ( ). , . '7' 1, NaN; '11'3. '1' 10, 0 .


, , :


['1', '7', '11'].map(numStr => parseInt(numStr));


Source: https://habr.com/ru/post/zh-CN456344/


All Articles