关于javascript:javascript你不知道的事儿

if( in )语句

let names = ['Lily', 'Barry', 'Dendi', 'Boogie', 'Lily'];

let nameNum = names.reduce((pre, cur) => {
     if (cur in pre) { //pre 中是否有 cur 属性
          pre[cur]++;
     } else {
          pre[cur] = 1; //为 pre 这个对象增加 cur 属性,并且赋值为 1
            }
          return pre;
}, {}) //reduce(), ES6数组归并办法,这里初始值设置为一个空对象

console.log(nameNum); //{Barry: 1,Boogie: 1,Dendi: 1,Lily: 2  }

if ( key in obj) 意思是 obj 中是否有 key 属性 ,有则返回 true, 没有则返回 false。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理