Home > 前端技术 > 两段“邪恶”的代码,模仿需谨慎……

两段“邪恶”的代码,模仿需谨慎……

  1. Array.prototype.toggle = function(val){
  2.     return this[(this[0] == val)|0]
  3. }
  4.  
  5. el.className = ["class1","class2"].toggle(el.className);
  1. Array.prototype.switch = function(val){
  2.     return this[(this.indexOf(val) + 1) % this.length];
  3. }
  4.  
  5. el.className = ["class1","class2","class3"].switch(el.className);

月影 前端技术

  1. 4mm
    August 17th, 2009 at 21:49 | #1

    太邪恶了 orz

  2. September 4th, 2009 at 20:18 | #2

    你好。我对第二段代码有点疑问,不知能不能解答下:
    1、switch是js的保留字吧?能用来当函数名么?
    2、this.indexOf(val)中的this是指数组吧?数组能用indexOf么?

    期待博主的解答,如果可以的话希望把解答发到我邮箱(nearpost@qq.com)里,谢谢了

  3. boozhidao
    September 25th, 2009 at 23:27 | #3

    第二个好像可以取代第一个吧.

    第一个里用了 (this[0] == val)|0
    将bool型转换成0,1,有点意思!

  4. boozhidao
    September 25th, 2009 at 23:31 | #4

    switch的问题是: 如果数组里有重复值的话,可能返回的不是自己需要的。

    飘过。。。