ES6的Array.from()和Array.fill()方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

ES6的Array.from()和Array.fill()方法

麦豇豆   2020-03-28 我要评论

今天处理数据时用到了Array.from()和Array.fill()方法,平时用的不多,这里记一下。

 

我的需求是要把字符串'abc',处理为[{exaple: 'abc_001.bcd'}, {exaple: 'abc_002.bcd'}, {exaple: 'abc_003.bcd'}]

处理方法如下:

let arr = new Array(3).fill('abc');
arr = Array.from(covers, (item, index) => { return { example: `${item}_00${index + 1}.bcd` } });

  

一、Array.fill()

Array.fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

例子:

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

参考:https:/https://img.qb5200.com/download-x/developer.mozilla.org/zh-CNhttps://img.qb5200.com/download-x/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

二、Array.from()

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

例子:

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

  参考:https:/https://img.qb5200.com/download-x/developer.mozilla.org/zh-CNhttps://img.qb5200.com/download-x/docs/Web/JavaScript/Reference/Global_Objects/Array/from

 

END--------------------------

你藏在我衣服的針線裡面,我藏在你口袋裡面。

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们