简体   繁体   English

如何在点符号中使用变量,如方括号符号

[英]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.我一直在 Javascript 中使用方括号表示法来创建和调用关联数组。

In this example, I understand that square bracket notation allows you to use a variable to call a certain object 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).不能使用以点表示变量(短期使用eval ,你不想做的)。 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.点表示法还限制了您可以访问的属性名称,因为属性名称必须是有效的 JavaScript 标识符。 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.例如,如果您有一个名为my prop (或者更好的是my%prop )的属性,那么不使用括号表示法就无法访问它,因为在大多数情况下它会导致语法错误。

The Member Operators page on MDN explains this a bit further. MDN 上成员运营商页面对此进行了进一步解释。

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.会导致错误的输出,因为p在这里不被视为变量。

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.这对于在 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.我制作了一个函数来通过点表示法设置变量,在 angular 2 中,但这也可以在 vanilla javascript 中使用,只需稍作修改。

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.如果路径不存在,它只是优雅地退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM