如何在map函数中获取项索引

时间:2017-03-02 11:46:44

标签: javascript reactjs ecmascript-6

我将地图分开,现在我很困惑如何获取索引。

function digPow(n, p) {
  var m = n;
  var i, sum = 0;
  var j = 0;
  var l = n.toString().length;
  var digits = [];
  while (n >= 10) {
    digits.unshift(n % 10);
    n = Math.floor(n / 10);
  }
  digits.unshift(n);
  for (i = p; i < l + p; i++) {
    sum += Math.pow(digits[j], i);
    j++;
  }
  if (sum % m == 0) {
    return sum / m;
  } else
    return -1;
}

alert(digPow(89, 1))

1 个答案:

答案 0 :(得分:0)

像这样写:

const renderList = (status, i) => {
   //how to get the index here?
   console.log('status', status, i)
}

return(
   typeList.map(renderList)
)

检查此示例:

function fun(item, i){
  console.log('item', item, i);
}

a = [1,2,3,4,5];

a.map(fun);

检查反应组分:

class App extends React.Component { 

    _createList(item, index) {
       return <div>{item}: {index}</div>
    }

    render() {
        return (
            <div>
                {[1,2,3,4,5].map(this._createList)}
            </div>
        )
    }
}


ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'>