Experienced to find out that this code works in several browsers:

var countsByStatus = { '': 23, // неизвестный статус 'started': 45, 'draft': 3, 'accepted': 23, 'hold': 2345, 'fixed': 2, 'published': 345 } 

The number of elements with different statuses is stored here, and some may be without status. Their number is added to the element with the key "empty string", which means "no status" . This approach looks simple and clear, but I'm not sure if it is correct, is it supported everywhere?

Translation of this question .

  • @diraria add a link to the original in the comments, if it is already at the bottom of my question?) - AivanF.
  • This is a special comment, the system will process it and add a link on the enSO page of the question to this question. more on the meta . - diraria
  • Опытным путём выяснил, что этот код работает в нескольких браузерах question begins with humor. Same syntax, darling, really so didn't know what works? - Goncharov Alexander
  • @GoncharovAleksandr is a translation of the question, I have already removed many inaccurate statements from it. - AivanF.

1 answer 1

The fact is that associative arrays (in which the index can be not only a number, dictionaries) in many languages ​​work with key hashes, and the empty string also has a hash: md5('') == d41d8cd98f00b204e9800998ecf8427e . With the support of this functional problems should not be, as long as this solution fits the meaning of your problem.

For completeness of the answer, we will consider related questions on the use of empty strings as keys:

 o = {...} // какой-нибудь объект/словарь o. = 2; // обращение как к полю объекта с пустой строкой не сработает o.'' = 2; // так тоже o[''] = 2; // только как к словарю 

Other examples of use:

 o[null] // вернёт o['null'] o[undefined] // вернёт o['undefined'] 

The fact is that null and undefined are special objects in JS, and not some values ​​that have a hash, when translated to a string, they turn into their names. You can convert null and undefined to the empty string '' like this:

 key = key || ''; 

And in order to bring non-string types to a string, you can simply add an empty string:

 key = '' + key; 

In this case, note that 0 will turn into an empty string '' , while the string '0' remains itself: '0' .

Translation of this answer and some comments.

  • What kind of ad-lib about hashes and associative arrays? - Grundy
  • @Grundy don't like something? And this is not ad-libbing, but “Translation of this answer and some comments” - the second comment on the original question. In my opinion, interesting information worth mentioning. - AivanF.
  • Yes, it is not applicable to javascript. The question is, after all, about a specific language - Grundy