JS Test(44道)总结

记录-复习

Posted by cici on October 1, 2017

题目来自javascript-puzzlers


1.reduce

reduce

没有设置初始值的空数组使用reduce方法会抛出错误
reduce的callback函数有四个参数,preValue,curValue,curValue-index,array,如果没有设定初始值,reduce开始时第一个值为preValue,第二个为curValue

2.map&parseInt

reduce

map默认参数有两个,回调函数和回调函数的this值 该回调函数有三个默认值,curValue、index和array parseInt()可以传有两个参数值,string和radix(基数)

reduce

parseInt()的radix为0时,算作基数为10

3.运算符顺序

reduce

三元运算符优先级低于+运算符

4.JS中能表示的最大整数

reduce

2^53是JS能正确计算而不失精度的最大整数,再加就丢失精度无法判断大小了

5.稀疏数组

reduce

js中,当数组为稀疏数组时,遍历数组时会跳过“坑位”,如图数组中

0 in array //true
3 in array //false

根据Array.prototype.map 的 polyfill.可以看出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Array.prototype.map = function(callback, thisArg) {
        var T, A, k;
        if (this == null) {
            throw new TypeError(' this is null or not defined');
        }

        var O = Object(this);
        var len = O.length >>> 0;
        if (typeof callback !== 'function') {
            throw new TypeError(callback + ' is not a function');
        }
        if (arguments.length > 1) {
            T = thisArg;
        }
        A = new Array(len);
        k = 0;
        while (k < len) {
            var kValue, mappedValue;
            if (k in O) {   //attention! 首先检查这个索引值是不是数组的一个属性
                kValue = O[k];
                mappedValue = callback.call(T, kValue, k, O);
                A[k] = mappedValue;
            }
            k++;
        }
        return A;
    };

6.switch()中的表达式

switch

严格比较时,String实例与字符串不一样

7.余数的正负号随第一个操作数

switch

8.关于if() & == & === 的理解

switch

if([]) 的含义:[]是否为“真值”
js里的“真值”很好判断,因为“假值”总共只有6个:

false,undefined,null,0,”“(空字符串),NaN

if([] == true) 的含义:[]与true是否相等。true会先转换为1 使用==,在类型不同的情况下会进行类型转换,然后再比较, (注意null==undefined

而使用===,绝对相等,需要类型相同并且值相同,比较前没有操作

9.隐式转换

隐式转换

[ ]==![ ]result为true
[] == !true // ! 操作符的优先级高于 == ,所以先执行 ! 操作 [] == false // !true 得到的是 false
[] == 0 //比较规则1:如果值为true或false,则转成1或0来继续比较
[] == 0 //执行左侧的 [] 的 valueOf 方法,而 [] 是对象,所以 [].valueOf() 返回本身 []
"" == 0 //执行左侧的 [] 的 toString 方法,[].toString() 返回 ““
0 == 0 //比较规则2:如果一个值是数字,一个值是字符串,则把字符串转换为数字,再进行比较,”” 转成数字是 0。 最终是执行 0 == 0 ,结果为 true 。

10.

11.

12.arguments

arguments

但是!当函数参数涉及到 any rest parameters, any default parameters or any destructured parameters 的时候, 这个 arguments 就不在是一个 mapped arguments object 了…..

1
2
3
4
5
6
7
8
9
function sidEffecting(ary) {
  ary[0] = ary[2];
}
function bar(a,b,c=3) {
  c = 10
  sidEffecting(arguments);
  return a + b + c;
}
bar(1,1,1)     //12

13.prototype

f.prototype 是使用使用 new 创建的 f 实例的原型.而 Object.getPrototypeOf 是 f 函数的原型.

1
2
a === Object.getPrototypeOf(new f()) // true
b === Function.prototype // true

14.function.name

Function.name Functin.name是只读属性

15.emmmmmm…又是转换

16.js数组

js允许数组最后一项带一个,

17.Date

Date Date/parse

18.function.length

一个function(Function 的实例)的 length 属性就是函数签名的参数个数, 所以 b.length == 0.另外 Function.length 定义为1.

19.神奇的min/max