0

在 MEAN 框架的启动代码中,有一行代码如下所示

if (!!~this.roles.indexOf('*')) {

它位于 shouldRender 函数中的 public/modules/core/services/menus.client.service.js 文件中。

var shouldRender = function(user) {
        if (user) {
            if (!!~this.roles.indexOf('*')) {  //Here is the code
                return true;
            } else {
                for (var userRoleIndex in user.roles) {
                    for (var roleIndex in this.roles) {
                        if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
                            return true;
                        }
                    }
                }
            }
        } else {
            return this.isPublic;
        }

        return false;
};
4

1 回答 1

0

它通过将“*”转换为布尔值来评估是否找到了“*”。它是纯 Javascript。

~[1, 2, 3, 4].indexOf(4)
//returns -4 (bit inversion of 3)

indexOf当元素存在时返回 0, 1, 2, 3...。位反转将这些值分别转换为 -1、-2、-3、-4、...。

当元素不存在时,返回-1。通过位反转,0 仍然存在。

因此,当元素存在时,您会得到一个非零值。当元素不存在时,你得到 0。

通过添加!!,您将值转换为布尔值(0 是假值,!0 是真,!!0 是假;x(如果不是零)是非假值,!x 是假,!!x 是真的)。

所以可以理解为:如果'*'在this.roles ...

于 2014-12-31T01:59:44.463 回答