Skip to content

Instantly share code, notes, and snippets.

@fundon
Created January 28, 2015 15:37
Show Gist options
  • Save fundon/90c5df8f5f77a77ed341 to your computer and use it in GitHub Desktop.
Save fundon/90c5df8f5f77a77ed341 to your computer and use it in GitHub Desktop.
JavaScript Tips

ECMAScript 标准

请解释以下结果:

  null == 0 // false
  null > 0 // false
  null >=0 // true
  [] == 0 // true
  • == 操作符看 http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

    • null == 0 由于 null0 类型不一样,ToPrimitive 时不一样,ToNumber 时相同,所以 null == 0 返回 false

    • [] == 0 先进行类型判断,[] Object 类型,先 ToPrimitive 获取原始值,([]).toString() = '', 在进行类型转换 ToNumber

      Number(([]).toString()) == 0 // true

  • > 从上面可得,其实 null == 0 null > 0 null < 0 三者的结果相同,都是 false

  • >=> 多了一步判断,上面例子如果 null < 0 = false, undefined, 则 >= 返回 true, 反正为 false

this - 执行环境,上下文对象,apply call 可以改变上下文执行对象

对象,继承

  • JS 的世界一切皆对象
  • 可以通过 mixin,也可以通过原型链来对对象进行扩展

简单例子:

var a = {};
var b = {
  say: function () {},
  walk: function () {}
};
for (var k in b) {
  a[k] = b[k];
}

function A() {}
function B() {}
A.prototype = B.prototype;

在 nodejs 的文件之间共享(交换)数据

  • global
  • 内存,文件存储,数据库等。

nodejs 后台相关库

  • 数据库模块
  • 数据操作方法集
  • http, 加密、stream
  • ...

nodejs 中 js 新特性

  • 关注 V8 动态,新的语法 ES5, ES6

module.exports 和 exports 区别

exports 是对 module.exports {} 的引用, 当 require 是,返回的是 module.exports, 如果要对一个模块 export 的类型进行变东, 就要修改 module.exports,而不是 exports

# a.js
exports = module.exports = function () {}
# c.js
exports.a = require('./a')

# b.js
var a = require('./a')
a() //
var c = require('./c');
c.a()//

NodeJS 的异常抛出的处理方案

try {} catch(e) { /* save(e); */ } 

NodeJS为什么有内存问题

请对下面的数据
[{name:’jch’, age:30, score:90, sex: 1},{ name:’oh’, age:31, score: 80, sex:1}, {name:’jia’, age:27, score: 70, sex:0} .....] 进行重组操作:
筛选年龄大于给定数据的用户,返回
以name为key,转化为对象。
以转化后的对象为目标,切换为以sex为key的分组数据(即sex为key,但value包含全部符合条件的对象)

使用 lodash 函式库

var newUsersByName = _.indexBy(_.filter(users, function (u) {return u.age > 20; }), 'name');
var newUsersBySex = _.indexBy(newUsersByName, function (u) { return u.sex; });

获取三个页面数据,并处理

可以接触 async , bluebird, promis 工具进行处理,当然也可以使用 co 工具,再结合 stream 进行数据变换

伪代码

co(function *() {

var a = yield getPromise(1);
var b = yield getPromise(2);
var c = yield getPromise(3);

// 数据变换
var na = transform(a)
var nb = transform(b)
var nc = transform(c)

// ...

})();

与其他语言相比

异步,回调,io 无阻塞。 库多,浏览器端,后台更加友好。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment