求解一下这个代码是什么意思

我的逻辑性有点差,还在学习阶段,这个代码有点看不懂,想请教下大家

                        if($scope.userList.findIndex(it => {
                            return it.accountID == item.accountId
                                    }) != -1) {
                                    item.checked = true
                                } else {
                                    item.checked = false
                              }
阅读 3.4k
7 个回答

userList中存在accountIditem中一样的元素,则将item中的checked置为true

在$scope.userList中查找accountId 是 item.accountId的项,有的话返回true,没有返回false。这个代码缩进有点乱啊

新手上路,请多包涵

$scope

这个代码就是找到userList中,accountId与 item.accountId一样的user的索引。

findIndex返回一个数字,表示索引

索引等于 -1,表示这样的user不存在,索引大于-1,表示存在。

如果存在这样一个user, 那么 item.checked设为true,反之 设置为false.

findIndex 是返回一个符合条件的元素在数组中的位置,不存在返回-1。

这段代码是判断 userList 中是否有指定 accountId的对象

findIndex 参考文档

if($scope.userList.findIndex(it => {return it.accountID == item.accountId}) != -1) {
    item.checked = true
} else {
    item.checked = false
}

先看 it => {return it.accountID == item.accountId} 他的结果 为 布尔值 true或false
在看 $scope.userList.findIndex( true或false ) 的结果

如果不等于 -1  执行  item.checked = true  
等于 -1或其他值  执行 item.checked = false 

按说应这样写:

item.checked = $scope.userList.findIndex(it => {return it.accountID == item.accountId}) != -1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题