如何将环境传递给地图?

时间:2017-08-27 13:29:55

标签: javascript ecmascript-6

我有两个问题:
1.当我将rows传递给checkEdge时,为什么我无法将rowIndex传递给checkEdge? 2.我如何才能访问createBoardcheckEdge的所有参数/变量,而不必将它们全部作为checkEdge(cell, cellIndex, rowIndex, width, height)传递 ?
尝试了checkEdge.apply(arguments)checkEdge.bind(this),但它没有用。

const checkEdge = function(cell, cellIndex, rows, rowIndex, width, height) {
  console.log(rows) // <--- logs undefined.
  console.log(rowIndex) // <--- works as expected.
  if(rowIndex === 0 || rowIndex === height-1) {
    return {value: 0, birth: false}
  }
  else if(cellIndex === 0 || cellIndex === width-1) {
    return { value: 0, birth: false }
  }
  else {
    return { value: Math.round(Math.random()), birth: false }
  }
}

const createBoard = ({width,height}) =>
Array.from({length: height}, 
  (rows, rowIndex) => Array.from({length: width}, (cell, cellIndex) => 

    checkEdge(cell, cellIndex, rows, rowIndex, width, height)
  ) 
)

2 个答案:

答案 0 :(得分:1)

  

为什么我可以将rows传递给checkEdge而我可以将rowIndex传递给checkEdge

你可以,而且你可以。问题只是rowsundefined,就像内部cell中的Array.from一样。请注意,您是从零创建数组(只是一个有长度但没有元素的对象),还没有值。

  

我如何才能访问createBoardcheckEdge的所有参数/变量,而不必将它们全部作为checkEdge(cell, cellIndex, rowIndex, width, height)传递?

您无法使用arguments因为它们不存在于箭头功能中。您可以使用rest语法,但在这里也不会特别有用。通常,虽然可以使用允许我们编写Ramda library的辅助函数(例如来自point-free code),但显式参数传递在这里更简单(并且更可读)。

答案 1 :(得分:0)

您可以使用spread / rest语法:

"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack": "^2.7.0"