0

Please explain, why this code it's not allowed in javascript and how to make it.

var p = "inputText";
regError.p

This will give me undefined but

regError.inputText 

will give me a correct result.

Rbex
  • 1,519
  • 6
  • 24
  • 50

3 Answers3

1

You can do it by using bracket notation:

regError[p]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

CD..
  • 72,281
  • 25
  • 154
  • 163
1

If you have an object like this

var regError = {
    inputText : 'something'
}

and you want to access it with a variable, you'll have to use bracket notation

var p = "inputText";

var result = regError[p]; // returns "something"
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Use with bracket notation:

regError[p]

You can check the difference between them here and there

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231