[‘1‘, ‘2‘, ‘3‘].map(parseInt) what & why ?

1. 基础函数

  • Map 函数:map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
var array1 = [1,4,9,16];
const map1 = array1.map(x => x *2);
console.log(map1);

输出结果:

Array [2,8,18,32]

如下我们看一下map 函数的完整定义:

  /**
     * Calls a defined callback function on each element of an array, and returns an array that contains the results.
     * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

回调函数的第一个参数是当前值,第二个参数是当前值的序号,第三个参数是当前数组。

function myparse(frist, second, third) {
    console.log(frist);
    console.log(second);
    console.log(third);
    return 1;
}

console.log(['1', '2', '3'].map(myparse));

结果如下:
在这里插入图片描述

  • parseint 函数: parseInt() 函数可解析一个字符串,并返回一个整数。
    函数定义如下:
/**
 * Converts a string to an integer.
 * @param s A string to convert into a number.
 * @param radix A value between 2 and 36 that specifies the base of the number in numString.
 * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
 * All other strings are considered decimal.
 */
declare function parseInt(s: string, radix?: number): number;

函数的第一个参数接收一个字符串值,第二个参数可选。表示要解析的数字的基数。该值介于 2 ~ 36 之间。

如果省略该参数或其值为 0,则数字将以 10 为基础来解析。如果它以 “0x” 或 “0X” 开头,将以 16 为基数。

如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN。

2. 试题解析

由上面对于两函数的解析我们可以清楚看出该题的答案为:

在这里插入图片描述
map 函数产生三次调用,分别为:
parseInt(‘1’,0) 基数值为 0 按照十进制进行解析,所以值为 1
parseInt(‘2’,1) 基数值小于 2 ,所以值为 NaN
parseInt(‘3’,2) 基数值为2 ,字符串值不在有效的值域空间,所以值为NaN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值