开发者

How to use variables in dot notation like square bracket notation

I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain obje开发者_Python百科ct in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'


You can't use variables in dot notation (short of using eval, which you don't want to do). With dot notation the property name is essentially a constant.

myObj.propName
// is equivalent to
myObj["propName"]


The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

item.x // is this the property "x" or do I have to look up variable "x"?


If you use numbers to access an array you have to use the brackets:

item[0]

var k = 0;
item[k]

as

item.0

doesn't work (wrong syntax).

If you use a string

item["key"]

var p = "key";
item[p]

equals

item.key

In the latter context

var p = "key";
item.p

would cause a wrong output as p is not treated as a variable here.


You actually can now.

In this case you can use square brackets to use a variable for dot notation.

console.log(item.[x])

This is especially useful for use in Typescript.


the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:

var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...


I made a function to set variables by dot notation, in angular 2, but this could also be used in vanilla javascript, with minor modifications.

class Utility {
    static setByDot(_obj, _path, _val) {
        return _path.split('.').reduce(function (prev, curr, _idx, _arr) {
            if ( _idx == (_arr.length-1) && prev ) {
                prev[curr] = _val;
            }

            return prev ? prev[curr] : null
        }, _obj || self);
    }
}

So you can just call

Utility.setByDot( _obj, 'foo.bar', 'value' );

And then

console.log( _obj.foo.bar );

Output, if path existed

string(6) 'value' 

If path doesnt exist, it just exits gracefully.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜