在Reactjs中获取对象数组的长度

时间:2019-04-18 23:00:48

标签: arrays reactjs object

我有一个对象数组:

 # R Shiny app demo - display PDF in app as reference document 
 library(shiny) 
 # Simple shiny layout for demo sake 
 ui <- (fluidPage( 
 sidebarLayout( 
     sidebarPanel( 
         h5("use case - embed a pdf the app - embed as a local pdf") 
       ),  
     mainPanel( 
         tabsetPanel( 
             # using iframe along with tags() within tab to display pdf with scroll, height and width could be adjusted 
             tabPanel("Reference",  
                                          tags$iframe(style="height:400px; width:100%; scrolling=yes",  
                                                                           src="test.pdf")), 
             tabPanel("Summary"), 
             tabPanel("Plot") 
           ) 
   )) 

 )) 




 server <- function(input, output) {

 }

 shinyApp(ui = ui, server = server)

将其设置为状态,然后在我的RangeSlider组件中进行渲染:

const boxOptions = [
  { 0: "$250", 1: "$500", 2: "$750", 3: "$1000", 4: "$1250", 5: "$1500" },
  { 0: "$500", 1: "$750", 2: "$1000", 3: "$1250", 4: "$1500", 5: "$2000" },
  { 0: "$750", 1: "$1000", 2: "$1250", 3: "$1500", 4: "$2000", 5: "$2500" },
]

当我尝试在onChange处理程序上获取其长度时,我不确定:

 state = {
    boxOptions: boxOptions,
    tier: 0
  };
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <RangeSlider label='What sort of box are you after?' onChange={this.handleBoxChange} min={0} max={5} defaultValue={this.state.boxIndex} marks={this.state.boxOptions[this.state.tier]} step={null} />
      </div>
    );
  }

这是为什么?

Link to Sandbox

1 个答案:

答案 0 :(得分:3)

this.state.boxOptions[this.state.tier].length

this.state.boxOptions[this.state.tier]可以工作并返回{ 0: "$250", 1: "$500", 2: "$750", 3: "$1000", 4: "$1250", 5: "$1500" },但是Object没有属性.length,这就是为什么它返回undefined的原因。

如果需要该对象的属性总数,可以使用:

Object.keys(this.state.boxOptions[this.state.tier]).length

Object.keys(object)将为您返回对象中所有键的数组