2016-07-28 33 views
2

的索引I有一個js片段,其產生一個錶行與JavaScript數組地圖功能如何確定的長度和當前項

TD S作爲如下

    var cols = this.props.cols; 
        data = this.state.data 

        return data.map(function (item) { 
         var cells = cols.map(function (colData) { 
          console.log(colData); 
          return <td>{item[colData.key]}</td>; 
         }); 


         return <tr key={item.Id }>{cells}</tr>; 
        }); 

我想確定最後一列,並想添加一個特定的按鈕td 如何獲取cols.map(函數(coldata)中的單元格長度,不確定是否能夠通過這種方法完成它

+0

想進去cols.map的cells.length(函數( coldata) – Kalanamith

+0

然後'cols.length'應該幫助.. – Rayon

回答

2

Map會注入兩個您目前未使用的參數。完整的回調簽名是(element,index,wholeArray)。然後你可以在數組上調用.length並將其與當前元素索引進行比較。

+0

是的它的工作 – Kalanamith

+0

感謝您接受其他人的答案,這是我的一樣,甚至說這樣的話:p – probablyup

+0

修復它........ ....................... – Kalanamith

2

這樣的事情會工作。作爲yaycmyk提到的地圖功能,可採取3個ARGS ..

1. the iterated item 
2. the index of the item 
3. the array that is being iterated on. 

我只是指標只是比較長 - 1

   return data.map(function (item) { 
        var cells = cols.map(function (colData, idx, arr) { 
         return (idx === arr.length -1) 
           ? <td><button /></td> 
           : <td>{item[colData.key]}</td>; 
        }); 


        return <tr key={item.Id }>{cells}</tr>; 
       }); 
相關問題