[英]What does this syntax mean in JavaScript return {hello: “world”}[something]
I saw this syntax in some code 我在一些代码中看到了这种语法
function parseMessage(error) {
return {
15: 'Faulted'
}[error];
}
I have never seen a function be invoked with an array is that what this means ? 我从未见过用数组调用函数是什么意思?
There is no array involved there. 那里没有数组。
It creates an object, then accesses the value of one of the object's properties by square bracket notation, and then returns that value. 它创建一个对象,然后使用方括号表示法访问该对象的属性之一的值,然后返回该值。
It is equivalent to: 它等效于:
function parseMessage(error) {
var myData = {
"15": 'Faulted'
};
var result = myData[error];
return result;
}
The above function is creating an object and then returning value of property using bracket notation 上面的函数创建一个对象,然后使用括号表示法返回属性值
Example: if value of error
is 15
then function will return 'Faulted'
. 示例:如果
error
值为15
则函数将返回'Faulted'
。 See DEMO 见演示
this function internally use a JavaScript Object Literal , 此函数在内部使用JavaScript Object Literal ,
Object literals are used as a means of encapsulating data, enclosing it in a tidy package to minimize the use of global variables which can cause problems when combining code.
对象文字被用作封装数据的一种方式,将其封装在一个整洁的包中,以最大程度地减少使用全局变量的可能性,这可能会在组合代码时引起问题。
Object literals are formed using the following syntax rules: 对象文字是使用以下语法规则形成的:
As Object literal is usable as a Associative Array 作为对象文字可用作关联数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.