数组中第一个不重复的值

var firstUniqChar = function(s) {
   const arr= _.countBy(s)
   for(const [i,k] of Array.from(s).entries()){
       if(arr[k]===1){
           return i
       }
   }
    return -1
};

firstUniqChar([1,1,2,3,4,4]).  //2

解析:

_.countBy(str)    //{1: 1, 2: 1, 3: 1}
Array.from('hello')   //['h','e','l','l','o']
Array.from(1,2,3,4)   //['1','2','3','4']
obj={1:1,2:2,3:3}
Object.ontries(obj)   //[['1',1],['2',2],['3',3]]

Array.from用法:

1、实现数组的浅拷贝。

2、将对象转换数组

请注意:1.object中必须有length属性,返回的数组长度取决于length长度
       2.key必须是数值

let obj = {
        0: 'hellow world',
        1: 'xiaoming',
        2: 'xiaohong',
        'length': 3
    } 
let arr = Array.from(obj)
console.log(arr);    ['hellow world', 'xiaoming', 'xiaohong']

Object.entries()用法:

Object.entries() 可以把一个对象的键值以数组的形式遍历出来,结果和 for…in 一致,但不会遍历原型属性。

1-传入对象

const obj = { name: ‘colin’, age: ‘18’ };
console.log(Object.entries(obj)); // [[‘name’, ‘colin’], [‘age’, ‘18’]]
每一个键值对对应一个数组,最后再存入到一个数组中。
2 – 传入数组

const arr1 = [1, 2, 3];
console.log(Object.entries(arr1)); // [[‘0’, 1], [‘1’, ‘2’], [‘2’, ‘3’]]
将数组中的下标与值对应存到一个数组,最后再存入到一个数组中。
2.2 – 数组(数组中包含对象)

const arr1 = [{ a: 1 }, 2, 3];
console.log(Object.entries(arr1)); // [[‘0’, { a: 1 }], [‘1’, ‘2’], [‘2’, ‘3’]]

2.3 – 数组(数组中的值全部为对象)

const arr2 = [{ a: 1 }, { b: 2 }, { c: 3 }];
console.log(Object.entries(arr2));// [[‘0’, { a: 1 }], [‘1’, { b: 2 }], [‘2’, { c: 3 }]]
3 – 字符串

const str1 = ‘123’;
console.log(Object.entries(str1)); // [[‘0’, ‘1’], [‘1’, ‘2’], [‘2’, ‘3’]]
4 – 数字、浮点数

const num = 123;
console.log(Object.entries(num)); // []

const float1 = 12.3;
console.log(Object.entries(float1)); // []
可见:输出值都为空数组

5 – 将 Object 转化为 Map
new Map() 构造函数接受一个可迭代的 entries 。 借助 Object.entries 方法你可以很容易的将 Object 转换为 Map:

const obj = { name: ‘xixixi’, age: ‘123’ };
console.log(Object.entries(obj)); // [[‘name’, ‘xixixi’], [‘age’, ‘123’]]
const map = new Map(Object.entries(obj));
console.log(map); // Map {‘name’ => ‘xixixi’, ‘age’ => ‘123’}

for in 与 for of 的区别:

for in 是ES5标准,遍历的是key(可遍历对象,数组和字符串的key)注:不推荐数组使用

for of 是ES6标准,遍历的是value(可遍历对象,数组和字符串的value)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值