ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-06-05 11:30:23  阅读:186  来源: 互联网

标签:function map what console 函数 number parseInt


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

标签:function,map,what,console,函数,number,parseInt
来源: https://blog.csdn.net/nanmudage/article/details/117588852

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有