简体   繁体   中英

How to access a hash inside of an array by key

I'm looking at this code I am not able to get the value of 'start' in the hash.

 w[l] = w[l] || [];
    w[l].push({
        'gtm.start':
            new Date().getTime(),
        event: 'gtm.js'
    });

I thought I could do:

w[l].start

or

w[l]['start']

But I get undefined errors.

w is passed in as a parameter, and it is a window object.

Working JsBin: https://jsbin.com/zilado/1/edit?js,console

So lets say you start with an empty array at w[1] , w itself is also an array.

You then push an Object to that array so w[1] is an array with an Object in it, that object has what your looking for, and you can access it like so:

var w = [];
w[1] = [];


w[1].push({'gtm.start': new Date().getTime()});

console.log(w[1][0]['gtm.start'])

w[l] is an array w[l] = w[l] || []; w[l] = w[l] || [];

Then you push an object to that array w[l].push({ ...

So you can access that object property with w[l][0]['gtm.start'] (assuming that the array is empty when you pushed the object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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