简体   繁体   中英

Confusion in the object and array for Node.js

I have the following code:

    var dataArray = [];

    switch (request_url.query.group) {
        case 'returning': 
            dataArray = {};
            var returning = _.filter(result, function(result) {
                return (result.sessions.length > 1) ? true : false;
            });
            //Am I setting the object dataArray here?
            dataArray.returning = returning.length; 
            //Am I setting the array dataArray here?
            dataArray['new'] = result.length - returning.length; 
            break;

I have confusion regarding dataArray here. The first line of code declares an array and in the switch case an object of the same name is declared. What is the 'new' and 'returning' values set and whom do it respectively belong to, the array or the object? Also, is object a super class of array in Node.js?

What is the 'new' and 'returning' values set and whom do it respectively belong to, the array or the object?

They'll belong to the Object . The Array is only referenced by dataArray up until this line:

dataArray = {};

After that, dataArray will only be a reference the Object while the Array would become unreachable and available for garbage collection.


Note: If you were wanting dataArray to be an " Array of Object s ," you can assign the Object to an index of dataArray :

dataArray[0] = {};

And set the properties similarly:

dataArray[0].returning = ...;
dataArray[0]['new'] = ...;

Also, is object a super class of array in Node.js?

Yes. Array s inherit from Object s because Array.prototype is an Object . MDN has a good summary of the prototype chain , which is JavaScript's inheritance model.

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