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,449
  • 6
  • 23
  • 48

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..
  • 68,981
  • 24
  • 147
  • 156
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
  • 303,455
  • 27
  • 380
  • 377
0

Use with bracket notation:

regError[p]

You can check the difference between them here and there

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211