JS篇 学习笔记

 

ECMA Script API:

Array.prototype.splice(start, deleteCount, value ...)

  数组操作中有:push、pop、unshift左移入、shift左进出;splice不仅可以完成删除操作,而且还可以从中间插入:当deleteCount参数为0时就可以将后面的多个参数添加进来;

 

  正则表达式中,匹配分为两类:

  1) 匹配字符

  如:\s, \d, \w等

  2) 匹配位置

  如:\b,^, $, (?=...), (?!...)

  这类往往用于断言:如果匹配的话,则要满足这样的规则,匹配的指针不会向前进或者后退。如:/\w(?=\d)/g表示匹配字母后跟随一个数字的子串。

// 断言:匹配字母下一位是非1的数字;
"a1b2cd3ef".match(/[a-zA-Z](?=\d)(?!1)/g)    // ["b", "d"]
// 矛盾了:要求匹配项的以数字开头,还的是:[a-zA-Z]
"a1b2cd3ef".match(/(?=\d)[a-zA-Z]/g)       // null

// 将数字串,转换为每3位用逗号分隔的国际化表示
"0123456789".replace(/\d{1,3}(?=(\d{3})+$)/g, "$&,")  // "0,123,456,789"

 

String.prototype.match(regexp)

  分两类情况:

  1) 正则含有g选项,如果不匹配返回null,否则返回所有匹配的字符串。(不包括Group匹配子串)

  2) 正则不含有g选项,如果不匹配返回null,否则返回一个数组,元素0为匹配的字符串片段,后面的元素为匹配的Group子串。该数组含有两个属性:index代表匹配的位置,input代表被匹配的字符串本身。

 

String.prototype.replace(string or regexp, replacement)

  如果是字符串,则不转换为正则;如果是正则,则replacement可以是以下:

  1) 字符串:其中的$代表特殊含义:$1, $2, ...代表多个Group匹配子串, $&代表匹配的整串,$`代表匹配左侧、$'代表匹配右侧;

// 因为/\d/匹配了a1b,所以1被a1b替换
"a1b".replace(/\d/, "$`$'")      // "aabb"
// 此时/\d/匹配a1b
"a1b".replace(/\d/, "$`-$'")     // "aa-bb"

  2) 函数:参数如下:参数0为匹配的整串,然后为Group子串,然后为Group子串的位置index,最后为被匹配的字符串。

 

 

即时编译的几种方式:

1. eval(' ... ')

2. new Function(' ... ')

3. setTimeout(' ... ', 0)              // 不推荐

4. <script type='text/javascript'> ... </script>  // 通过JS创建script节点,append到head节点中

/*
eval:
1. 在当前的function context中执行,可以修改值;
2. 字符串中的最后一句表达式可以作为eval的返回值;
3. 返回值如果不是简单类型,需要用"(...)"小括号围绕起来;
*/
(function(){
  var o1 = eval('var s1 = "test"; ({ a1: s1 }) ');
  console.log(o1, s1);
})();
/* 
new Function():
1. 执行时将全局作用域作为function context;
*/
var a1 = "outer";
(
function(){ var a1 = 'test'; var f1 = new Function('console.log(this === window);'); // true var f2 = new Function('return a1;'); // a1 is not defined console.log(f1(), f2()); })();

 

posted on 2015-02-06 16:37  diydyq  阅读(133)  评论(0编辑  收藏  举报

导航