前言

日常开发过程中常常会遇到模仿数据填充的问题。也就是造一些假数据,不便本人调试和开发。由此,整顿了罕用的数据填充的办法,在本人学习的过程中,也分享给更多开发者。一起学习,一起加油,一起精进。

fill()

fill() 办法用一个固定值填充一个数组中从起始索引到终止索引内的全副元素。不包含终止索引。

let arr  = Array(10).fill('1')//[ "1", "1", "1", "1", "1", "1", "1", "1", "1", "1" ]let obj = Array(2).fill({name:'叫我詹躲躲',age:18})//[{ name: "叫我詹躲躲", age: 18 },{ name: "叫我詹躲躲", age: 18 }]

copyWithin()

copyWithin() 办法浅复制数组的一部分到同一数组中的另一个地位,并返回它,不会扭转原数组的长度。填充的都是undefined.

 const arr = [...Array(10)].copyWithin(0)//[ undefined, undefined, undefined, undefined, undefined ]

还能够依据索引复制数组的值到另一个数组

let arr = ['a', 'b', 'c', 'd', 'e'];console.log(arr.copyWithin(0, 3, 4));[ "d", "b", "c", "d", "e" ]

keys()

keys() 办法用于从数组创立一个蕴含数组键的可迭代对象。
如果对象是数组返回 true,否则返回 false。

//填充数组const arr = [...Array(10).keys()]//[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Array.from()

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

Array.from(arrayLike[, mapFn[, thisArg]])
参数

arrayLike想要转换成数组的伪数组对象或可迭代对象。

mapFn 可选 如果指定了该参数,新数组中的每个元素会执行该回调函数。

thisArg 可选 可选参数,执行回调函数 mapFn 时 this 对象。

四种填充程序数据办法(其余数据亦可)

const arr = Array.from(Array(10)).map((item,index)=>index)//[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const arr = Array.from(Array(10), (item, index)=>index)//[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const arr = Array.apply(null, Array(10)).map((item, index)=>index)//[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const arr = Array.from({length:10},(item,index)=>index)

map()

一个Map对象在迭代时会依据对象中元素的插入程序来进行 — 一个 for...of 循环在每次迭代后会返回一个模式为[key,value]的数组。
应用map填充程序数据

// const arr =[...Array(10)].map((item,index)=>index)[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Array.of()

Array.of() 办法创立一个具备可变数量参数的新数组实例,而不思考参数的数量或类型

const arr = Array.of(1, 2, 3);   // [1, 2, 3]

Array.of()Array 构造函数之间的区别在于解决整数参数:Array.of(7) 创立一个具备单个元素 7 的数组,而 Array(7) 创立一个长度为7的空数组(留神:这是指一个有7个空位(empty)的数组,而不是由7个undefined组成的数组)。

const arr = Array(7);          // [ , , , , , , ]const arr1 = Array(1, 2, 3);    // [1, 2, 3]

ArrayBuffer()

ArrayBuffer 对象用来示意通用的、固定长度的原始二进制数据缓冲区。
有时候还会建设固定长度的原始二进制数据缓冲区。能够应用ArrayBuffer,它是一个字节数组。

const buffer = new ArrayBuffer(8);console.log(buffer.byteLength);//8console.log(buffer);//{ byteLength: 8 }

Object.keys()

Object.keys() 办法会返回一个由一个给定对象的本身可枚举属性组成的数组,数组中属性名的排列程序和失常循环遍历该对象时返回的程序统一 。

let arr = Object.keys(Array.apply(null, {length:10})).map((item=>+item));[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

创立值为String的数组

let arr = Object.keys([...Array(10)]);//[ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ]

能够创立长期数据进行展现

let yData = Array.from({ length: 5 }, v => Math.random() * 10240) //[ 7513.437978671786, 5167.373983274039, 3814.0122504839223, 981.9482320596001, 4330.3850800180335 ] let xData = Array.from({ length: 5 }, (v, w) => '叫我詹躲躲' + w)//[ "叫我詹躲躲0", "叫我詹躲躲1", "叫我詹躲躲2", "叫我詹躲躲3", "叫我詹躲躲4" ]

小结

可将办法扩大创立更多简单的数据。此处只是简略的举例,更便于了解,也能帮忙更多地人把握。