if index is set

Certified Associate Developer

Hello,

How I can check if index is set 

example: local!startchart[5]

if 5 in this array is not set throw 0 for example ?

  Discussion posts and replies are publicly visible

Parents
  • with(
        local!startChart: {
            1,
            2,
            3,
            4
        },
        local!chartIndex: 2,
    
        if (
            local!chartIndex > count(local!startChart), 
            0, 
            index(local!startChart, local!chartIndex, 0)
        )
    )

    I think the index() function will return null if it is not set. But you can replace the last parameter, using 0 in order to return zero if the index is not set.

    Additionally, you can perform a check before using the value for chartIndex if it is within the bounds of the number of elements of the local!startChart.

    Using the array notation with "variable[index]" format is also not a good practice because the index might be invalid. 

Reply
  • with(
        local!startChart: {
            1,
            2,
            3,
            4
        },
        local!chartIndex: 2,
    
        if (
            local!chartIndex > count(local!startChart), 
            0, 
            index(local!startChart, local!chartIndex, 0)
        )
    )

    I think the index() function will return null if it is not set. But you can replace the last parameter, using 0 in order to return zero if the index is not set.

    Additionally, you can perform a check before using the value for chartIndex if it is within the bounds of the number of elements of the local!startChart.

    Using the array notation with "variable[index]" format is also not a good practice because the index might be invalid. 

Children
  • I think it's simpler than this. fn!index() will look for an item at the index provided and, if not found, can return a default value:

    a!localVariables(
      local!myArray: {1,2,3,4,5},
      fn!index(local!myArray, 7, 99)
    )

    In this example, I have an array of 5 elements, and I'm looking for the value in the 7th position - which doesn't exist - so I return 99 instead.

    Or have I missed some nuance here?