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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)