码迷,mamicode.com
首页 > 编程语言 > 详细

Array数组语法系列: Array.from()

时间:2018-01-19 11:48:15      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:元素   gen   pos   zh-cn   tle   title   generate   UI   val   

Array.from() 可以通过以下方式来创建数组对象:

  • 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象)
  • 可迭代对象(可以获取对象中的元素,如 Map和 Set 等)

Array.from() 方法有一个可选参数 mapFn,让你可以在最后生成的数组上再执行一次 map 方法后再返回。也就是说 Array.from(obj, mapFn, thisArg) 就相当于 Array.from(obj).map(mapFn, thisArg);

 

 

示例
Array from a String
Array.from(‘foo‘); 
// ["f", "o", "o"]
Array from a Set
let s = new Set([‘foo‘, window]); 
Array.from(s); 
// ["foo", window]
Array from a Map
let m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m); 
// [[1, 2], [2, 4], [4, 8]]
Array from an Array-like object (arguments)
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [1, 2, 3]
Using arrow functions and Array.from
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);      
// [2, 4, 6]


// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

 

Array数组语法系列: Array.from()

标签:元素   gen   pos   zh-cn   tle   title   generate   UI   val   

原文地址:https://www.cnblogs.com/laopang/p/8315432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!