2020-08-25
描述
从一个对象或其他迭代(对象,数组、字符串、集合等)中创建一个由键值对数组组成的数组。
提示
- 检查 Symbol.iterator是否被定义
- 如果是的话,使用 Array.prototype.entries()为给定的可迭代对象获取他的迭代器
- 使用 Array.from()将结果转换为一个包含键值对数组的数组
- 如果 Symbol.iterator没有在obj中定义,则使用Object.entries()进行替代
代码
const toPairs = obj =>
  obj[Symbol.iterator] instanceof Function && obj.entries instanceof Function
    ? Array.from(obj.entries())
    : Object.entries(obj);
示例
获取键值对数组:
toPairs({ a: 1, b: 2 });  // [ ["a", 1], ["b", 2] ]
toPairs([2, 4, 8]);  // [ [0, 2], [1, 4], [2, 8] ]
toPairs('shy');  // [ ["0", "s"], ["1", "h"], ["2", "y"] ]
toPairs(new Set(['a', 'b', 'c', 'a']));  // [ ["a", "a"], ["b", "b"], ["c", "c"] ]
 
         ME!
                
                ME!
             链滴
                
                链滴