你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?

在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。

HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性

尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。


当前回答

这并不总是一个好主意,但您可以用简洁的表达式转换大多数内容。这里重要的一点是,JavaScript中并不是每个值都是对象,所以这些表达式会成功,而对非对象(如null和undefined)的成员访问将失败。特别要注意typeof null == "object",但你不能null. tostring(),或("name" in null)。

将任何东西转换为数字:

+anything
Number(anything)

将任何东西转换为无符号四字节整数:

anything >>> 0

将任何东西转换为字符串:

'' + anything
String(anything)

将任何东西转换为布尔值:

!!anything
Boolean(anything)

同样,使用不带“new”的类型名对于String、Number和Boolean的行为不同,返回一个基本数字、字符串或布尔值,但使用“new”将返回“盒装”的对象类型,这几乎是无用的。

其他回答

嗯,我没有读完整个主题,尽管这对我来说很有趣,但让我做一点小小的捐赠:

// forget the debug alerts
var alertToFirebugConsole = function() {
    if ( window.console && window.console.log ) {
        window.alert = console.log;
    }
}

数字也是对象。所以你可以做一些很酷的事情,比如:

// convert to base 2
(5).toString(2) // returns "101"

// provide built in iteration
Number.prototype.times = function(funct){
  if(typeof funct === 'function') {
    for(var i = 0;i < Math.floor(this);i++) {
      funct(i);
    }
  }
  return this;
}


(5).times(function(i){
  string += i+" ";
});
// string now equals "0 1 2 3 4 "

var x = 1000;

x.times(function(i){
  document.body.innerHTML += '<p>paragraph #'+i+'</p>';
});
// adds 1000 parapraphs to the document

如果您在google上搜索关于给定主题的像样的JavaScript参考,在查询中包含“mdc”关键字,那么您的第一个结果将来自Mozilla Developer Center。我没有随身携带任何离线参考资料或书籍。我总是使用“mdc”关键字来直接找到我要找的东西。例如:

谷歌:javascript数组排序mdc (在大多数情况下,你可以省略“javascript”)

更新:Mozilla开发者中心已重命名为Mozilla开发者网络。“mdc”关键字技巧仍然有效,但很快我们可能不得不开始使用“mdn”来代替。

我要说的是自执行函数。

(function() { alert("hi there");})();

因为Javascript没有块作用域,如果你想定义局部变量,你可以使用一个自执行函数:

(function() {
  var myvar = 2;
  alert(myvar);
})();

在这里,myvar不会干扰或污染全局作用域,并且在函数终止时消失。

如果你喜欢类似CLOS的基于类的OO, Joose是一个不错的对象系统。

// Create a class called Point
Class("Point", {
    has: {
        x: {
            is:   "rw",
            init: 0
        },
        y: {
            is:   "rw",
            init: 0
        }
    },
    methods: {
        clear: function () {
            this.setX(0);
            this.setY(0);
        }
    }
})

// Use the class
var point = new Point();
point.setX(10)
point.setY(20);
point.clear();