分类 javascript 下的文章

Javascript中escape/encodeURI/encodeURIComponent有何区别

escape()

已在 ECMAScript v3 中废弃。

encodeURI()

如果你需要编码一个URL(如:放进href属性中),就调用这个函数:

encodeURI("http://www.google.com/a file with spaces.html")

获得结果:

http://www.google.com/a%20file%20with%20spaces.html

不要使用encodeURIComponent,否则你会得到如下结果:

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

如果你想编码一个URL参数的值,就调用encodeURIComponent:

param1 = encodeURIComponent("http://example.com/?a=12&b=55")
url = "http://domain.com/?param1=" + param1 + "&param2=99";

获得如下结果

http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99

Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).

es6的co模块generators回调过程是否是异步的

实际编程中遇到一个问题:

var s = ...;
co(function* fn(){
    // IO操作1
    s = yield SomeFunc();
});

// IO操作2,没有使用generators,如事件操作等
var e = SomeOpenFileFunc();
e.on("read", (err, data) => {
    console.log(data);
});
e.on("close", (err) => {
    // 关闭文件
});

那么,是IO1先执行完成后再执行IO2呢(类似同步的流程),还是IO1和IO2并行执行呢(类似异步的过程)?这是个问题,有空试一下。
感觉应该是后者,我感觉co里面的那个回调是异步的,所以执行完co这一句以后就直接返回了,继续执行SomeOpenFileFunc()。