2

I faced a strange problem, even if I push some content to an array with custom index keys, its still show as an empty array. If I know the index then I can reach the content.

function search (source, pattern) {
  let regexp    = new RegExp(pattern, 'g');
  let messages  = [];
  let match;

  while ((match = regexp.exec(source)) !== null) {
    let date  = match[2];
    let ms    = parseDate(date).getTime();
    if(Object.prototype.toString.call(messages[ms]) !== '[object Array]')
      messages[ms] = [];

    messages[ms].push(match[0])
  }
  console.log(messages);
  console.log(messages[1414860420000]);
}

Calling this on my source with my pattern will wind multiple matches and it will push them into the correct sub array in the main array. But if after this I try console.log(messages); it will return [ ] instead of a list of [object Array]s. However calling an existing key I can reach the data inside the messages array. What am I missing? Why the content is "not visible" in the array?

EDIT:

The exact reason why the values attached as a property and not as an member of the array is because the numbers I wanted to use are bigger than the maximum allowed size

So while this works:

var fruits = ['apple', 'banana', 'kiwi'];

fruits[23] = 'pear';

document.getElementsByTagName('p')[0].innerHTML = fruits.toString();
<p></p>

This wont work:

var fruits = ['apple', 'banana', 'kiwi'];

fruits[53454657567573] = 'pear';

document.getElementsByTagName('p')[0].innerHTML = fruits.toString();
<p></p>
Community
  • 1
  • 1
NoNameProvided
  • 8,608
  • 9
  • 40
  • 68

1 Answers1

4

Change let messages = []; to let messages = {}; You aren't using messages as an array. You are using it as an object to store property/values on. While an array is also an object so the properties do get stored on the array, console.log() gets fooled when you use an array rather than a plain object.

console.log() thinks you want to view the contents of the array. But there are no actual array elements on messages. You will see that messages.length === 0. The array is actually empty which is what console.log(messages) shows you.

On the other hand, if you make messages a plain object, then console.log() will show you the property/value pairs on the object.


FYI, this won't change the behavior, but you could simplify by changing this:

if(Object.prototype.toString.call(messages[ms]) !== '[object Array]')

to this:

if (!messages[ms])

since all you're trying to see is whether the property has been previously initialized to an array or not.

jfriend00
  • 683,504
  • 96
  • 985
  • 979