Javascript 如何在点符号中使用变量,如方括号符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7102704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use variables in dot notation like square bracket notation
提问by Paul Sham
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'
回答by nnnnnn
You can't use variables in dot notation (short of using eval
, which you don'twant to do). With dot notation the property name is essentially a constant.
不能使用以点表示变量(短的使用eval
,你不希望这样做)。使用点符号,属性名称本质上是一个常量。
myObj.propName
// is equivalent to
myObj["propName"]
回答by Zack The Human
The short answer is: you can'taccess a property using dot notationunless 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 notationbecause it would lead to a syntax error is most cases.
点表示法还限制了您可以访问的属性名称,因为属性名称必须是有效的 JavaScript 标识符。例如,如果您有一个名为my prop
(或更好,my%prop
)的属性,那么在不使用括号表示法的情况下将无法访问它,因为在大多数情况下它会导致语法错误。
The Member Operators page on MDNexplains 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"?
回答by sjngm
If you use numbers to access an array you have touse 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
这里没有将其视为变量。
回答by Alex Pacurar
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...
回答by Karl Johan Vallner
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.
如果路径不存在,它只是优雅地退出。