2

I have a custom object that I would like to create an array of. When creating my array it creates an occurrence with empty properties, I understand why, but I would like to avoid this. I realize I could just delete the occurrence with the empty properties, but is there a better way?

function FileToPassBack(path, originalFileName, modifiedDate, newFilename) {
    if (!(this instanceof FileToPassBack)) {
        return new FileToPassBack(namepath, originalFileName, modifiedDate, newFilename);
    }
    this.Path = path;
    this.OriginalFileName = originalFileName;
    this.ModifiedDate = modifiedDate;
    this.NewFileName = newFilename;
}

function PostSelectedItems() {
    var allFilesToPassBack = new Array(new FileToPassBack());

     $('#fileNamesTable').find('tbody>tr:visible')
                         .each(function (index, element) {
                                var row = $(this);
                                if (row.find('input[type="checkbox"]').is(':checked'))
                                {
                                    var path = row.find('.pathTDClass').html();
                                    var originalFileName = row.find('.originalFileNameTDClass').html();
                                    var modifiedDate = row.find('.modifiedDateTDClass').html();
                                    var newFileName = row.find('input[class="newFileNameTDClass"]').val();

                                    var currentFileToAdd = new FileToPassBack(path, originalFileName, modifiedDate, newFileName)
                                    allFilesToPassBack.push(currentFileToAdd);
                                }
                            });

    //post path, original file name, modified date, new file name
    var objectAsJSON = JSON.stringify(allFilesToPassBack);
}

I am new to JS, so excuse me if I am way off track.

2 Answers 2

1

new Array(number)

Creating a new array with a number will initialize it with a certain number of empty elements:

var a = new Array(5);
// a = ['','','','',''];

thus when you push it will add a new entry

a.push("a");
// a = ['','','','','', 'a'];

The best practice is not to use new Array, instead use [] syntax as it is more performant.

var allFilesToPassBack = [];

JSON Stringify

although it works, you need to be aware that you are stringify-ing an array not a JSON in your example code.

Update

why [] is more performant than new Array() and considered a best practice.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

why its a best practice?

The new Array() doesn't add anything new compared to the literal syntax, it only wraps the array with an object wrapper that is not needed, only adding overhead of calling the Array constructor and creating an object wrapper around the array.

additionally defining a function Array() {} in the code, new Array() will start creating new instances from this function instead of creating an array, its an edge case, but if you need an array, just declare it with [].

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

There are ton of sources, but i'll keep it minimal for this update. new was introduced to the language as it is "familiar" to other languages, as a prototypal language, the new syntax is useless and wrong, instead the language should have Object.create. but thats a different topic, you can read more about it from experts like Kyle Simpson or Douglas Crockford.

Sign up to request clarification or add additional context in comments.

16 Comments

If your claim about "best practice" and performance is true, could you back it up with a trustful source?
@trincot of course, i can explain why its more performant, and i can look for sources. i'll update my answer accordingly.
OK, I am curious, because on my FireFox it makes no performance difference whether I do new Array() or [ ]. There are fluctuations of one being 2% faster than the other, but it varies in both ways.
@trincot dude [] creates an array. new Array() creates an array wrapped in an object wrapper, constructed from the Array function. [] doesnt construct anything. it only creates an array in memory at runtime. I believe i explained clearly by now, now you believe whatever you want.
@trincot we are talking about arrays not objects, objects have differences between the two as you can change the settings of the object via its constructor call. arrays have no difference only you can pass a number of params. you dont accept a resource from YUI javascript experts but give me a stackoverflow answer?!
|
0

I think, though am unsure what your actual problem is, that you are calling var allFilesToPassBack = new Array(new FileToPassBack()); to initialize your array? You don't need to do that.

Try replacing that line with this instead.

var allFilesToPassBack = []

That will init an empty array than you can then pushto in your jquery each loop.

6 Comments

This worked. Thanks. My formal training is C#, so I want everything to be strongly typed.
Mine is too, takes a while to remember JS is not strongly typed :)
@BrandonHunt not that i mind or anything, but im wondering why is this the accepted answer? its answered after my answer, and my answer explains the reason why you should use [] with code example aswell ..
@AhmadBamieh I answered before you did. That is probably why.
@AhmadBamieh Can you read and do math? It says on mine, "answered 58 minutes ago" It says on yours "answered 52 minutes ago" ... Simple logic would tell you that my answer has been around longer which would mean that I answered first. I don't really care if you answer is accepted or mine is (just want to help OP), but don't try to say you answered first.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.