0

One of my friend had a discussion regarding this,

Consider:

var myString = new String("Hello world");
alert(myString["length"]); // 11

myString["simpleExample"] = true;
alert(myString.simpleExample); // true

myString["spaced Example"] = false;
alert(myString["spaced Example"]); // false

Taking all the properties into an array,

var props = ["length","simpleExample","spaced Example"];

now, this will,

for (var i = 0; i < props.length; i++) {
alert(myString[props[i]]);
}
// alerts each property individually: 11 true false

This doesn't work,

for (var i = 0; i < props.length; i++) {

            alert(myString.props[i]);
}
// alerts each property individually: 11 true error/nothing

Is there any way to access those properties/keys(having spaces in them) by a dot notation or simply no for array ([ ]) operator is made solely for this?

EDIT:

The question was asked to my friend in an interview, and the interviewer hinted at a solution by using eval, but I am unable to make out that thing.

Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105

2 Answers2

0

If you allow yourself to use eval (which you really, really shouldn't for such a trivial reason), then it is indeed possible:

for (var i = 0; i < props.length; i++) {
    alert(eval("myString." + props[i]));
}

Putting it here only for argument's sake. Don't ever use this in production. And it still won't work with properties with disallowed characters in them (like "spaced Example").

Dzinx
  • 55,586
  • 10
  • 60
  • 78
-1

myString.props[i] means something entirely different than myString[props[i]]. myString.props[i] is the item with name/index i of the props property of myString. Since myString (presumably) does not have a property props, this will result in an error.

The myString[..] notation allows you to get a property of myString using an expression, for example the expression props[i]. There is no way to do the same thing with dot notation. Dot notation is always literal. myString.props always refers to the props property of myString and nothing else.

Dot notation is also further limited to require property names which are valid variable names. E.g. obj.0 does not work because 0 by itself is not a valid identifier; i.e. you could also not do var 0. Therefore you need to use obj[0]. Other than that, obj.0 and obj[0] are entirely equivalent, but the [] subscript notation allows a wider range of expressions.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    Please read the question carefully where props[i] corresponds to a string – Akshay Khandelwal Sep 16 '15 at 12:51
  • @Akshay I don't know what you're trying to tell me. – deceze Sep 16 '15 at 13:14
  • @Akshay The code as posted will not work because the syntax is flat out wrong and means something different than the OP is trying to achieve. The problem of spaces in keys isn't even relevant, if that's what you're trying to get at. – deceze Sep 16 '15 at 13:22