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.
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.
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.
Related
I am puzzled why this following bit of code will return mutations of both the local and global array:
var globalarray = [1,2,3];
function test(){
let localarray = globalarray;
localarray.push(4);
console.log(localarray);
console.log(globalarray);
}
setInterval(test, 2000);
Returns:
[1,2,3,4] for both
My impression was that localarray would be a copy of globalarray. I saw another answer that said in order to make a copy of an array you need to use .slice().reverse(), which seems like a workaround. Why does it not just create a new local copy? Is there a simple and efficient way to make a local copy of a global array? Otherwise it seems like making multiple mutations to a global array is terrible for performance.
The reason for this in your code is because you are simply telling your test function to point to the globalarray with the = operator. This is because in JavaScript, variable assignments do not inherently "copy" objects into the new variables; this might seem confusing, so just think of the = operator as a sign that points your code to the location of an object.
The only times that the = operator is making new copies is when you are working with primitive types. In those cases, you cannot inherently change what those objects are, so = is sufficient to make a copy like you would expect.
The reason for the .slice().reverse() is to work around the problem you are seeing. Another way you could do this is by using let localarray = globalarray.map(e => e), or as samee suggested, by using let localarray = [...globalarray]. The .map operator takes the function given to it as the first argument and applies it to every element, and then it stores the result in a different array at another location that is not the same as globalarray.
Keep in mind that these methods, and any others that might be suggested to you, are shorthand ways of doing
let localarray = new Array(globalarray.length);
for (let i = 0; i < globalarray.length; i++) {
localarray[i] = globalarray[i];
}
// localarray can now be freely modified because it does not point to the same array as globalarray
Also keep in mind that if you need to also create copies of the elements inside of the arrays, then you will have to use more comprehensive copying code. There are libraries that can do this sort of heavy-duty copying if you really need it.
In JavaScript (as in many other languages), objects are passed by reference. Arrays are also passed by reference (because an array is actually a type of object). So when you say: let localarrray = globalarray, you are actually setting localarray to a pointer that resolves to globalarray.
There are several strategies for obtaining a true copy. If you're trying to get a fresh copy of the original array, the Array prototype function of .map() is one of the most targeted tools for the job. It would look like this:
let localarray = globalarray.map(element => element);
Simple way to clone an array is just
let localarray = globalarray.slice();
I do it a different way to deep cloning:
clone: function() {
var clone = undefined;
var instance = this;
if ( XScript.is.xobject(instance) ) {
clone = {};
for ( var prop in instance ) {
if ( instance.hasOwnProperty(prop) ) {
var p = instance[prop];
if ( XScript.is.xobject(p) ) p = p.clone();
clone[prop] = p;
}//END IF this
}//END FOR prop
return clone;
}//END IF xobject
if ( XScript.is.xarray(instance) ) {
clone = instance.slice(0);
return clone;
}
return clone;
}//END FUNCTION clone
This clone will require you attaching the clone object to the object prototype and check to see if its an array, object, or other. I am not changing the function to fit all your needs because one should learn to somewhat how to change it and what to do instead of copy pasta. Plus it is just an example.
How can I manipulate the prototype of a predefined object (for example an Array) so that it does something when creating instances of that object?
Simply I want to alert('an array was created!') whenever an Array is instantiated.
You can set a new method on an array by adding it to the Array.prototype object:
Array.prototype.fizz = function () {
alert('works');
};
var arr = [];
arr.fizz();
However, this only allows you to create new methods, this does not allow you to extend existing methods*, nor does it allow you to override the Array constructor.
Be careful adding new methods to existing types. This can adversely affect the entire scripting environment, and cause unexpected behavior in some libraries. Although some might call it "bad practice", it's quite common to use polyfills for cross-browser compatibility, such as by creating Array.prototype.indexOf.
There is no such thing as a "newed" array, the word is "instantiated":
var a1, a2;
a1 = []; //a1 was instantiated with a new Array
a2 = new Array(); //a2 was also instantiated with a new Array
There is no cross-browser means of overriding the Array constructor.
* it's possible to wrap an existing method in a function so that, when called, the existing method performs its original functionality, in addition to the new functionality. Although this might be referred to as extending an existing method, it is in fact creating a new method.
You can try to override Array with your own function. It seems to work when doing new Array, but not when doing [].
(function() {
var _ac = Array;
Array = function() {
alert('an array was newed!');
return _ac.apply(this, arguments);
};
}());
DEMO: http://jsfiddle.net/DAg9A/
I would suggest the you just create an array namespace for it:
array = {};
array.create = function() {
alert("Created an array");
return [];
}
So whenever you create an array you use: array.create(); .
You should not, and in this case can not, change native functionality. You have to be in charge of every array creation.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create an empty object in JavaScript with {} or new Object()?
When I want to declare a new array I use this notation
var arr = new Array();
But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."
I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []? Or is it bad practice?
Is there a good reason to use var arr = []; instead of var arr = new Array();?
[] is:
shorter
clearer
not subject to new Array(3) and new Array(3,3) doing completely different things
cannot be overridden.
Example code:
var a = new Array(3);
var b = new Array(3,3);
Array = function () { return { length: "!" }; };
var c = new Array();
var d = [];
alert(a.length); // 3
alert(b.length); // 2
alert(c.length); // !
alert(d.length); // (still) 0
This code live - will try to create 4 alerts!
Mostly, people use var a = [] because Douglas Crockford says so.
His reasons include the non-intuitive and inconsistent behaviour of new Array():
var a = new Array(5); // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it
Note that there's no way with new Array() to create an array with just one pre-specified number element in it!
Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ].
Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().
The recommended practice is to use
var arr = [];
Already answered here
In javascript, you should use literal when you can.
var a = []; instead of var o = new Array();
var o = {}; instead of var o = new Object();
Similarly, don't do new String("abc");, new Number(1);, and so on.
JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays.
//Bad way to declare objects and arrays
var person = new Object(),
keys = new Array();
The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead.
Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation.
//Preferred way to declare objects and arrays
var person = {},
keys = [];
Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax.
//Preferred way to declare complex objects and arrays
var person = {
firstName: "Elijah",
lastName: "Manor",
sayFullName: function() {
console.log( this.firstName + " " +
this.lastName );
}
},
keys = ["123", "676", "242", "4e3"];
Best Practice
You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down.
The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, We Hardly new Ya.
This is how I do it now. It feels like a hazzle...
var broken_posts = new Object();
broken_posts.empty = new Array();
broken_posts.one = new Array();
var broken_posts = { empty: [], one: [] };
var broken_posts = {
empty: [],
one: []
};
The answers by Andru and Thilo are both correct, but perhaps some information on why is in order:
Avoid direct calls to the Array constructor: it's confusing and misleading. var a = new Array(5); returns [undefined,undefined,undefined,undefined,undefined], whereas var b = new Array('5'); returns ['5']. Or even var c = new Array(5,5); => [5,5].
Same applies for the direct object constructor. There's really no reason to create an object calling the basic object constructor. The only times you should use the keyword new is when creating a date object, or calling a self-made constructor function (and even in that case, there's no real need for the new keyword, there are alternative design patterns). Using the object literal {} is more common, allows for direct assignment of properties (and even methods). Besides, It's so much easier to create your objects in a JIT sort of way. Not only does it require less lines of code, with correct use of closures, or just for the one call, an object can get GC'ed once you're finished with it.
function iWantAnObject(obj)
{
if (obj instanceof Object)
{
return true;
}
return false;
}//function returns, obj is GC'ed
iWantAnObject({just:'some',rand:'Object',withA:function(){console.log('a method';}});
As opposed to this scenario:
var tempObj = new Object();
tempObj.just = 'some';//etc...
//etc...
iWantAnObjct(tempObj);
//tempObj isn't yet GC'ed
In the last example chances are: you accidentally create global variables, have various objects in memory that are no longer required, and, last but not least: isn't very in tune with the prototypal nature of JS.
I would prefer to use CoffeeScript instead.
Then you can do it this way:
broken_posts =
empty: []
one: []
When I need to declare a new array I use this notation
var arr = new Array();
But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."
I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []? Or is it bad practice?
Is there a good reason to use var arr = []; instead of var arr = new Array();?
Mostly, people use var a = [] because Douglas Crockford says so.
His reasons include the non-intuitive and inconsistent behaviour of new Array():
var a = new Array(5); // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it
Note that there's no way with new Array() to create an array with just one pre-specified number element in it!
Using [] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [].
Personally, I always use the [] syntax, and similarly always use {} syntax in place of new Object().
One significant difference is that [] will always instantiate a new Array, whereas new Array could be hijacked to create a different object.
(function () {
"use strict";
var foo,
bar;
//don't do this, it's a bad idea
function Array() {
alert('foo');
}
foo = new Array();
bar = [];
}());
In my example code, I've kept the Array function hidden from the rest of the document scope, however it's more likely that if you ever run into this sort of issue that the code won't have been left in a nice closure, and will likely be difficult to locate.
Disclaimer: It's not a good idea to hijack the Array constructor.
for maintainability, use []
The array literal is more predictable, as most developers use it. Most array usage out there will be using the literal, and there is value in having your code match up with what other developers use.
for empty arrays, use []
var ns = [];
var names = [ 'john', 'brian' ];
As shown here, using the literal for empty and a couple of known elements is fatster than the Array constructor.
for an array of known size, use new Array(size)
If the size is known, then using the Array constructor significantly improves performance. However it also means you have to deal with an array which already has 'undefined' filling
all it's values.
As shown here
// fill an array with 100 numbers
var ns = new Array( 100 );
for ( var i = 0; i < 100; i++ ) {
ns[i] = i;
}
This also works for very small arrays too.
No, there is actually no reason to use one notation over the other one for empty Arrays.
However, most browsers show a slightly better performance using x = []; than calling the Constructor.
If you need to create an Array with a specific size, you kind of need to use x = new Array(10); for instance, which would create an Array with 10 undefined slots.
var arr=[] uses the array/object literal
var arr = new Array() use the array/object constructor
The speediest way to define an array or object is literal way, because you don't need to call the constructor
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];
alert(arr1[0]); // 1
alert(arr2[0]); // 1
var arr3 = new Array(200);
var arr4 = [200];
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
Both are correct only. But most of the people use var a = []
Three Ways to Declare an Array in JavaScript.
method 1: We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available).
// Declare an array (using the array constructor)
var arlene1 = new Array();
var arlene2 = new Array("First element", "Second", "Last");
method 2: we use an alternate method to declaring arrays.
// Declare an array (using literal notation)
var arlene1 = [];
var arlene2 = ["First element", "Second", "Last"];
method 3: JavaScript also lets you create arrays indirectly, by calling specific methods.
// Create an array from a method's return value
var carter = "I-learn-JavaScript";
var arlene3 = carter.split("-");
There is a limit the constructor can take as arguments.
On most systems I encoutered the limit is 2^16 (2 bytes):
var myFreshArr = new Array(0,1,2,3 ..... 65536);
That will cause an error (too many arguments....)
When using the literal [] you don't have such problems.
In case you don't care about such big arrays, I think you can use whatever you prefer.
var array = [ 1, 2, 3, 4];
is sugar
var array = new Array(1, 2, 3, 4);
is salt
It's because new Array() is ambiguous. These are the correct constructors:
// Using brackets
[element0, element1, ..., elementN]
// Using new AND a list of elements
new Array(element0, element1, ..., elementN)
// Using new AND an integer specifying the array length
new Array(arrayLength)