将null转换成数组_Javscript数组快速填充数据的8种方法
前言
日常開發過程中經常會遇到模擬數據填充的問題。也就是造一些假數據,方便自己調試和開發。由此,整理了常用的數據填充的方法,在自己學習的過程中,也分享給更多開發者。一起學習,一起加油,一起精進。
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); //8 console.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" ]小結
可將方法擴展創建更多復雜的數據。此處只是簡單的舉例,更便于理解,也能幫助更多地人掌握。
總結
以上是生活随笔為你收集整理的将null转换成数组_Javscript数组快速填充数据的8种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mfc中嵌入python_Python
- 下一篇: canvas 实现图片局部模糊_Java