10取整操作也可以用按位操作
var x = 1.23 | 0; // 1
因为按位操作只支持32位的整型,所以小数点部分全部都被抛弃
11indexOf() 不需要再比较数字
const arr = [1, 2, 3];// 存在,等效于 > -1if (~arr.indexOf(1)) {}// 不存在,等效于 === -1!~arr.indexOf(1);
按位操作效率高点,代码也简洁一些 。也可以使用es6的 includes() 。但写开源库需要考虑兼容性的道友还是用 indexOf 比较好
12getter/setter 也可以动态设置吗?
class Hello { _name = 'lucy'; getName() { return this._name; } // 静态的getter get id() { return 1; }}const hel = new Hello();hel.name; // undefinedhel.getName(); // lucy// 动态的getterHello.prototype.__defineGetter__('name', function() { return this._name;});Hello.prototype.__defineSetter__('name', function(value) { this._name = value;});hel.name; // lucyhel.getName(); // lucyhel.name = 'jimi';hel.name; // jimihel.getName(); // jimi
130.3 - 0.2 !== 0.1 // true
浮点操作不精确,老生常谈了,不过可以接受误差
0.3 - 0.2 - 0.1 <= Number.EPSILON // true
14class 语法糖到底是怎么继承的?
function Super() { this.a = 1;}function Child() { // 属性继承 Super.call(this); this.b = 2;}// 原型继承Child.prototype = new Super();const child = new Child();child.a; // 1
正式代码的原型继承,不会直接实例父类,而是实例一个空函数,避免重复声明动态属性
const extends = (Child, Super) => { const fn = function () {}; fn.prototype = Super.prototype; Child.prototype = new fn(); Child.prototype.constructor = Child;};
15es6居然可以重复解构对象
const obj = { a: { b: 1 }, c: 2};const { a: { b }, a } = obj;
一行代码同时获取 a 和 a.b 。在a和b都要多次用到的情况下,普通人的逻辑就是先解构出 a,再在下一行解构出 b 。
16判断代码是否压缩居然也这么秀
function CustomFn() {}const isCrashed = typeof CustomFn.name === 'string' && CustomFn.name === 'CustomFn';
17对象 === 比较的是内存地址,而 >= 将比较转换后的值
{} === {} // false// 隐式转换 toString(){} >= {} // true
18intanceof 的判断方式是原型是否在当前对象的原型链上面
function People() {}function Man() {}Man.prototype = new People();Man.prototype.constructor = Man;const man = new Man();man instanceof People; // true// 替换People的原型People.prototype = {};man instanceof People; // false
如果您用es6的class的话,prototype原型是不允许被重新定义的,所以不会出现上述情况
19Object.prototype.__proto__ === null; // true
这是原型链向上查找的最顶层,一个 null
20parseInt 太小的数字会产生 bug
parseInt(0.00000000454); // 4parseInt(10.23); // 10
211 + null // 11 + undefined // NaNNumber(null) // 0Number(undefined) // NaN
22arguments 和形参是别名关系
function test(a, b) { console.log(a, b); // 2, 3 arguments[0] = 100; arguments[1] = 200; console.log(a, b); // 100, 200}test(2, 3);
推荐阅读
- 孝宣皇帝的皇后 孝钦皇太后是谁
- 宋代图书分类方法 古代私人书籍收藏的最大图书馆是
- 清朝十三阿哥胤祥的结局 历史上的十三阿哥胤祥福晋
- 适合微信端商城的营销手段有哪些?
- 善用沙盒虚拟机,测试有风险的程序让你无视木马病毒
- 好的金骏眉的特点,金骏眉品质鉴别
- CA证书服务器的搭建
- 再遭遇大流量的DDOS/CC攻击时为什么高防CDN是首选
- 喝什么菊花茶好,孕期喝菊花茶的注意事项
- 浑身是宝的普洱茶,五宝补肾茶配方