[翻译]High Performance JavaScript(018)
String Trimming 字符串修剪
Removing leading and trailing whitespace from a string is a simple but common task. Although ECMAScript 5 adds a native string trim method (and you should therefore start to see this method in upcoming browsers), JavaScript has not historically included it. For the current browser crop, it's still necessary to implement a trim method yourself or rely on a library that includes it.
去除字符串首尾的空格是一个简单而常见的任务。虽然ECMAScript 5添加了原生字符串修剪函数(你应该可以在即将出现的浏览器中看到它们),到目前为止JavaScript还没有包含它。对当前的浏览器而言,有必要自己实现一个修剪函数,或者依靠一个包含此功能的库。
Trimming strings is not a common performance bottleneck, but it serves as a decent case study for regex optimization since there are a variety of ways to implement it.
修剪字符串不是一个常见的性能瓶颈,但作为学习正则表达式优化的例子有多种实现方法。
Trimming with Regular Expressions 用正则表达式修剪
Regular expressions allow you to implement a trim method with very little code, which is important for JavaScript libraries that focus on file size. Probably the best all-around solution is to use two substitutions—one to remove leading whitespace and another to remove trailing whitespace. This keeps things simple and fast, especially with long strings.
正则表达式允许你用很少的代码实现一个修剪函数,这对JavaScript关心文件大小的库来说十分重要。可能最好的全面解决方案是使用两个子表达式:一个用于去除头部空格,另一个用于去除尾部空格。这样处理简单而迅速,特别是处理长字符串时。
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/, "");
}
}
// test the new method...
// tab (\t) and line feed (\n) characters are
// included in the leading whitespace.
var str = " \t\n test string ".trim();
alert(str == "tes
相关文档:
2、原型方式写类,原型方式继承
core js自身的对象系统就是采用原型方式(prototype based)继承的。或者说core
js没有采用常见的类继承(class
based)系统,而是使用原型继承来实现自己的对象系统。工作中我们也可以用原型方式来实现继承,代码复用以构建自己的功能模块。
/**
* 父类Polygon:多边形
*
*/
functio ......
Closure中文翻译为闭包.字面上来理解就是"封闭的包".(这是一句废话)
闭包是什么?
书面解释为:
所谓“闭包”,指的是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。
我认为闭包就是能够读/写函数内部的某些变量的子函数,并将这些变量保存 ......
常规的方法是将年月日取出,然后分别判断范围,然后就判断闰年2月的天数
可以通过new Date(string)的构造,比较年月日字符是否发生变化判断。
function CheckDate(text) {
if (!text) return false;
text = text.replace(/[\/-]0?/g, "/");
if (!text.match(/^\d{4}\/\d{1,2}\/\d{1,2}$/)) return true;
......
Conditionals 条件表达式
Similar in nature to loops, conditionals determine how execution flows through JavaScript. The traditional argument of whether to use if-else statements or a switch statement applies to JavaScript just as it does to other languages. Since different b ......
A Note on Benchmarking 测试基准说明
Because a regex's performance can be wildly different depending on the text it's applied to, there's no straightforward way to benchmark regexes against each other. For the best result, you need to benchmark your regexes on test strings o ......