简体   繁体   English

此语法在JavaScript中返回{hello:“ world”}的含义是什么[something]

[英]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: 对象文字是使用以下语法规则形成的:

  • A colon separates property name from value. 冒号将属性名称与值分开。
  • A comma separates each name/value pair from the next. 逗号将每个名称/值对与下一个分开。
  • There should be no comma after the last name/value pair. 姓氏/值对之后不应有逗号。 Most browsers won't object if you add it, but Internet Explorer prior to version 9 will generally trigger an error: 'Expected identifier, string or number'. 如果您添加大多数浏览器,它们不会反对,但是版本9之前的Internet Explorer通常会触发错误:“期望的标识符,字符串或数字”。

As Object literal is usable as a Associative Array 作为对象文字可用作关联数组

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

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