Javascript拥有两个相当强大而且受开发者喜爱的函数:split 与join 俩对立的函数。这俩函数能让string与array两种类型互换,也就是数组能被序列化为字符串,反之亦然。我们能把这俩函数发挥得淋漓尽致。下面就来探索里面的一些有趣的应用, 首先介绍一下这两个函数:
String.prototype.split(separator, limit)
separator把字符串分割为数组,可选参数limit定义了生成数组的最大length。
"85@@86@@53".split('@@'); //['85','86','53'];"banana".split(); //["banana"]; //( thanks peter (-: )"president,senate,house".split(',',2); //["president", "senate"]Array.prototype.join(separator)
可选参数separator把数组转换为一个字符串。如果不提供separator,那么就会把逗号做为这个参数值(就跟数组的toString函数一样)。
["slugs","snails","puppy dog's tails"].join(' and '); //"slugs and snails and puppy dog's tails"['Giants', 4, 'Rangers', 1].join(' '); //"Giants 4 Rangers 1"[1962,1989,2002,2010].join();
下面来看这些应用:
replaceAll
这个简单的函数不像原生的replace函数,它能作为一个全局的子字符串替换而不需要使用正则表达式。
String.prototype.replaceAll = function(find, replaceWith) { return this.split(find).join(replaceWith); }"the man and the plan".replaceAll('the','a'); //"a man and a plan"
对于小的字符串,它比单个字符替换的原生函数性能要弱一些(这里指的是正则表达式的两个额外的函数),但是在mozilla下,如果这个字符超过2个或3个字符话,这种使用函数要比正则表达式运行得更快。
occurences
该函数能取到子字符串匹配的个数。而且这种函数很直接不需要正则。
String.prototype.occurences = function(find, matchCase) { var text = this; matchCase || (find = find.toLowerCase(), text = text.toLowerCase()); return text.split(find).length-1; }document.body.innerHTML.occurences("div"); //google home page has 114document.body.innerHTML.occurences("/div"); //google home page has 57"England engages its engineers".occurrences("eng",true); //2repeat
该函数是从prototype.js 借鉴而来:
String.prototype.repeat = function(times) { return new Array(times+1).join(this); }"go ".repeat(3) + "Giants!"; //"go go go Giants!"
它的美妙之处就在于join函数的使用。焦点就在这个separator参数值,然后这个基础数组仅仅包含了一些未定义的value值。为了更清楚的说明这点,我们来重造一下上面的实例:
[undefined,undefined,undefined,undefined].join("go ") + "Giants
记住在join之前每个数组元素都会转换为一个字符串(这里就是一个空字符串)。这个repeat函数的应用是通过数组字面量定义数组的为数不多的不可行的应用。
新闻热点
疑难解答
图片精选