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

console.log(Array.from(Array(Math.round(Math.random()*10)), (x,k) => ({item:x,key:k}) ));

> Array [Object { item: undefined, key: 0 }, Object { item: undefined, key: 1 }

生成随机长度的一个数组

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

console.log(Array.from([1, 2, 3], (x,k) => ({item:x,key:k})));

> Array [Object { item: 1, key: 0 }, Object { item: 2, key: 1 }, Object { item: 3, key: 2 }]

console.log(Array.from(Array(3), (x,k) => ({item:x,key:k})));

> Array [Object { item: undefined, key: 0 }, Object { item: undefined, key: 1 }, Object { item: undefined, key: 2 }]

 

Array.from()模拟数据:

getData(selectCata){
  let count=Math.round(Math.random()*2);
  // let imgurl=`../../images/${count}.jpg`;
  return Array.from(Array(Math.round(Math.random()*20)),(v,k)=>({price:Math.round(Math.random()*20),sole:Math.round(Math.random()*20),img:count,pid:selectCata.id,id:selectCata.id+"_"+k,title:"分类"+selectCata.id+"菜品"+(k+1)}))
}

生成随机数组:

[{"price":10,"sole":4,"img":0,"pid":2,"id":"2_0","title":"分类2菜品1"},

{"price":20,"sole":11,"img":0,"pid":2,"id":"2_1","title":"分类2菜品2"},

{"price":3,"sole":1,"img":0,"pid":2,"id":"2_2","title":"分类2菜品3"},

{"price":14,"sole":8,"img":0,"pid":2,"id":"2_3","title":"分类2菜品4"}]

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from

posted @ 2019-01-16 10:54  Hakuna__Matata  阅读(433)  评论(0编辑  收藏  举报