在JavaScript ES6中是否存在初始化数组的功能方法?

时间:2018-07-26 01:42:31

标签: javascript ecmascript-6 functional-programming

我最终放弃了,并写了一个model = Sequential() model.add(Conv1D(filters=16,kernel_size=4,padding='same', input_shape=(window_size,1))) model.add(Bidirectional(LSTM(128, activation='sigmoid', return_sequences=True))) model.add(Bidirectional(LSTM(256, activation='sigmoid', return_sequences=True))) model.add(Dense(128,activation='tanh')) model.add(Dense(1)) 循环来初始化一个简单的对象数组,其中每个对象都有一个递增的计数器(for)作为对象的属性。换句话说,我只想要:

id

我希望可以将紧凑的语法放到return语句中。

var sampleData = [{id: 1},{id: 2},...];

6 个答案:

答案 0 :(得分:43)

Array.from()是执行此操作的好方法。您可以传递{length: somlength}对象或其他类似数组的对象以及定义每个项目的函数。该函数的第一个参数(将其称为_只是为了表明它未被使用)将是我们传入的数组中的项(但我们只传入了一个长度,因此意义不大),第二个参数i是索引,用于您的id

let sampleData = Array.from({length: 10}, (_, id) => ({id}))

console.log(sampleData)

答案 1 :(得分:13)

我通常这样做的是:

const data = Array(10).fill().map((v, i) => ({id: i + 1}))

fill确保它可以与map

一起使用

答案 2 :(得分:7)

您可以将spread运算符与Array一起使用,然后将每个undefined元素映射到所需的对象。

var arr = [...Array(10)].map((_,i)=>({id:i}));
console.log(arr)

答案 3 :(得分:5)

您正在寻找变形或反折–

// unfold : ((r, state) -> List r, unit -> List r, state) -> List r
const unfold = (f, init) =>
  f ( (x, next) => [ x, ...unfold (f, next) ]
    , () => [] 
    , init
    )
    
// sampleData : List { id: Int }
const sampleData =
  unfold
    ( (next, done, i) =>
        i > 25
          ? done ()
          : next ({ id: i }, i + 1)
    , 0
    )
    
console .log (sampleData)
// [ { id: 0 }, { id : 1 }, ... { id: 25 } ]

通过查看unfold在其他常见程序中的使用方式,您可以了解其工作原理–

// unfold : ((r, state) -> List r, unit -> List r, state) -> List r
const unfold = (f, init) =>
  f ( (x, next) => [ x, ...unfold (f, next) ]
    , () => []
    , init
    )
    
// fibseq : Int -> List Int
const fibseq = init =>
  unfold
    ( (next, done, [ n, a, b ]) =>
         n === 0
           ? done ()
           : next (a, [ n - 1, b, a + b ])
    , [ init, 0, 1 ]
    )
    
console .log (fibseq (10))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

unfold的实现只是一种可能性。修补并以您选择的方式实施–

// type Maybe a = Nothing | Just a    

// Just : a -> Maybe a
const Just = x =>
  ({ match: ({ Just: f }) => f (x) })

// Nothing : unit -> Maybe a
const Nothing = () =>
  ({ match: ({ Nothing: f }) => f () })

// unfold : (state -> Maybe (a, state), state) -> List a  
const unfold = (f, init) =>
  f (init) .match
    ( { Nothing: () => []
      , Just: ([ x, next ]) => [ x, ...unfold (f, next) ]
      }
    )

// fibseq : Int -> List Int
const fibseq = init =>
  unfold
    ( ([ n, a, b ]) =>
        n === 0
          ? Nothing ()
          : Just ([ a, [ n - 1, b, a + b ] ]) // <-- yikes, read more below
    , [ init, 0, 1 ]
    )
    
console .log (fibseq (10))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

我以[]作为元组在上面作弊。这使程序更短,但是最好对事物进行显式建模并考虑其类型。您用 functional-programming 标记了这个问题,因此值得一试,从我们的程序中删除这种隐式处理。通过将其显示为一个单独的步骤,我们隔离了一种不仅可以应用于unfold的技术,还可以应用于我们设计的任何程序–

// type Maybe a = Nothing | Just a
// type Tuple a b = { first: a, second: b }

// Just : a -> Maybe a
const Just = x =>
  ({ match: ({ Just: f }) => f (x) })

// Nothing : unit -> Maybe a
const Nothing = () =>
  ({ match: ({ Nothing: f }) => f () })

// Tuple : (a, b) -> Tuple a b
const Tuple = (first, second) =>
  ({ first, second })

// unfold : (state -> Maybe Tuple (a, state), state) -> List a  
const unfold = (f, init) =>
  f (init) .match
    ( { Nothing: () => []
      , Just: (t) => [ t.first, ...unfold (f, t.second) ] // <-- Tuple
      }
    )

// fibseq : Int -> List Int
const fibseq = init =>
  unfold
    ( ([ n, a, b ]) =>
        n === 0
          ? Nothing ()
          : Just (Tuple (a, [ n - 1, b, a + b ])) // <-- Tuple
    , [ init, 0, 1 ]
    )
    
console .log (fibseq (10))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

答案 4 :(得分:3)

.from()示例很好,但是如果您真的想发挥创造力,请查看此。

const newArray = length => [...`${Math.pow(10, length) - 1}`]
newArray(2)
newArray(10)

虽然非常有限

newArray(1000)
["I", "n", "f", "i", "n", "i", "t", "y"]

答案 5 :(得分:1)

您可以使用简单的递归过程来做到这一点。

const iter = (arr, counter) => {
  if (counter === 25) return arr;
  return iter([...arr, {id:counter}], counter + 1)
}
iter([], 0)