V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
tomheng
V2EX  ›  问与答

this.length >>> 0 ,这个语句经常在javascript中出现,大家有知道具体这个语句是有什么作用,已经>>>符号是一个运算符吗,还是其他什么?

  •  
  •   tomheng · 2012-01-04 10:13:25 +08:00 · 8676 次点击
    这是一个创建于 4517 天前的主题,其中的信息可能已经有所发展或是发生改变。
    8 条回复    1970-01-01 08:00:00 +08:00
    qiao
        1
    qiao  
       2012-01-04 10:26:30 +08:00
    位运算操作符之一,作用是向右位移一位,并用0填充。
    benzhe
        2
    benzhe  
       2012-01-04 10:51:02 +08:00
    this.length >>> 0 一般用于确保this.length是可运算的数值吧
    http://www.w3school.com.cn/js/pro_js_operators_bitwise.asp
    1502
        3
    1502  
       2012-01-04 11:27:20 +08:00
    功能应该与 ~~this.length 类似吧,转为number
    ambar
        4
    ambar  
       2012-01-04 12:15:32 +08:00
    # 相见

    首先,如果看到了这个用法,它可能是出现在一些库的 enumerable 的函数实现中,操作对象是 *伪数组对象* 或 *数组对象* , this 就指向两种可能对象(因为 JavaScript 函数的 call 和 apply 方法,可以改变 this 的指向)。

    # 运算符

    “>>>” 是无符号右移运算符,它保证结果为非负整数,这正是 length 的值所想要的(如果运算子为NaN,length 结果将为0,在后续代码中遍历对象也不会抛出异常)。

    详见 ES5 规范文档,文档的定义使得数组原型上的方法都能作用于伪数组上面:

    MDN Array.prototype.map 实现参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
    “Let len be ToUint32(lenValue)” :http://es5.github.com/#x15.4.4.19
    9.6 ToUint32 http://es5.github.com/#x9.6
    11.7.3 The Unsigned Right Shift Operator http://es5.github.com/#x11.7.3

    # 什么是伪数组对象(array-like object)?

    // 能用数字下标存取,带有 length 属性
    var o = {0:'foo',1:'bar',length:2}
    var each = Array.prototype.forEach

    // 如何简易地遍历伪数组
    each.call(o,function(n,i){
    console.log(n,i)
    })

    # 更普遍的样例

    伪数组在 JavaScript 中常见的主要有两类:

    // 经常会看到的做法,处理 NodeList 对象
    each.call( document.querySelectorAll('div'), function(el){
    doSomeThingWith(el)
    })

    // 又,处理 arguments 对象
    var foo = function(){
    return Array.prototype.join.call(arguments,',')
    }

    foo('yep','nope') === 'yep,nope'
    est
        5
    est  
       2012-01-04 12:15:43 +08:00
    应该和 this.length||0同样的作用。
    tomheng
        6
    tomheng  
    OP
       2012-01-04 14:13:34 +08:00
    tomheng
        7
    tomheng  
    OP
       2012-01-04 14:15:01 +08:00
    @est 作用不一样,this.length>>>0可以将大于等于0的数取整
    est
        8
    est  
       2012-01-04 14:45:44 +08:00
    @tomheng 这个学习了。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3661 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:00 · PVG 13:00 · LAX 22:00 · JFK 01:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.