ES6 array initialization

余生长醉 提交于 2021-01-27 21:21:51

问题


Very new to ES6. In ES5 I might do something like this

function newArray(){
   var data = [];
   for(var i = 0; i < 5; i++){
    data[i] = "test data " + i;   
   }
  return data;
}

x = newArray()

How would I do this in ES6 ? What I've got below is in error

 getData = () => ({
    let data = Array.from(new Array(5), (x, i) => "test data " + i)
    return {
        data
    }
})

回答1:


You create wrong the function with ES6

getData = () =>{
    let data = Array.from(new Array(5), (x, i) => "test data " + i)
    return {
        data
    };
}
console.log(getData())

You can fill an array using fill and map methods.

//arr.fill(value, start, end)
getData = () =>{
    let data = new Array(5).fill(0).map((a,i)=>"test data " + i);
    return {
        data
    };
}
console.log(getData())



回答2:


In ES6 it should be something like this:

const data = Array.from(new Array(5), (x, i) => "test data " + i);
// if you want to return an object with the field data mapped to your array
const getData2 = () => ({ data });
console.log(getData2());


来源:https://stackoverflow.com/questions/43469583/es6-array-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!