Where foo is a defined variable, why is it that the following code:
var array = [].push(foo);
when outputted, equals 1?
From my tests, outputting array will simply output the length of the array.
So the code:
var array = [10,20].push(foo);
would give a value of 3.
As a related question (and to clarify what my code intended to do), why does this not intuitively do what it appears to do, ie:
var array = [];
array.push(foo);
where outputting array gives the expected result of [foo]?
When you use push method it returns length of array. So when you do:
var array = [10,20].push(foo);
you get [10, 20, foo] length of this array is three. But as you say var array it stores returned length from push method in this variable.
Array.prototype.push() always returns the new number of elements in the array. It does not return this instance or a new Array instance. push() is a mutator actually changes the contents of the array.
instead you can try
var array, foo = 30;
(array = [10,20]).push(foo);
console.log(array)
push is a function and it returns an integer representing the length of the array.
Imagine the definition of this function as
int push(object obj);
When you do this:
var array = [].push(foo);
You are actually running the function and returning the value.
Because the return value of push is the new length of the array Documentation and examples.
In your second example, you cited outputting the array, which is going to give you the new array in both cases. However, the returned result of your second case is the new array length as well
var array = [];
array.push(foo); //If you do this in the console, you'll see that 1 gets returned.
console.log(array); //While this will print out the actual contents of array, ie. foo
The definition of push() method including two parts in javascript: Part 1: it adds one or more elements to the end of an array, part 2: it returns the new length of the array.
I think you are missing the part 2 in your understanding of this method.
Related
I have been watching PluralSight's Rapid JavaScript Training by Mark Zamoyta and I came across this. He showed these two examples. I've been trying to wrap my head around it, but still could not understand.
How is it able to capture the length of the entries after the array was created using new Array() method, seeing that it returned a blank array []. If it's blank like this [], shouldn't it return -1?
var entries = [1,2,3,4,5];
entries.length
=> 5
entries
=> [ 1, 2, 3, 4, 5 ]
var entries = new Array(5);
entries.length
=> 5
entries
=> []
var myArray = new Array(5);
When you define an array by passing the constructor an integer like above, memory is allocated for 5 slots in the array. If you examine the array, you will find:
console.log(myArray[1]);
=> undefined
console.log(myArray.toString);
=> ,,,,
As you can see, there are indeed five elements in the array, each of them undefined. So your array isn't "blank."
It is probably bad practice to initialize an array in this manner, as there just isn't a good use case for it. Pushing to the array will yield:
myArray.push("value");
console.log(myArray.toString);
=> ,,,,,value
...which is never what you want. I would advise initializing the array like below and forget that passing an integer to the constructor is even an option:
var myArray = [];
The length property of an array in JS is not calculated on the fly - it can also be set manually via the constructor or an assignment, and it's updated as objects are added or removed (Spec):
Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index[.]
It's a plain property that's kept up-to-date, not a calculation. Using the constructor new Array(5) initializes an array with length set to 5. You can also set it manually, which fills in undefined or truncates the array as needed:
var arr = [];
arr.length = 3;
// arr is now [undefined, undefined, undefined]
I haven't touched Javascript in a while and now I'm having trouble with basic arrays.
params=new Array();
params['return']='json';
alert(params.length);
This always returns 0 when I'm expecting 1. What's wrong with this?
Arrays use numerical indexes. When you use a string "index", it just adds a new property to the array object, but the new value isn't in the array.
Thus, the array is still empty, but you can access your value as you could with any other object.
Your code is equivalent to
var params = {}; //new object (not array)
params['return']='json'; //new property added to object
A few things:
You forgot var:
var params = new Array();
But an array takes numeric indices, so params['return'] is not really a member of the array but of the object that represents the array, so it doesn't affect the length.
You could use an object but objects have no length:
var params = {};
params['return'] = 'json';
To get the length though you can count the keys in that object and get the length of the resulting array:
var len = Object.keys(params).length;
Javascript arrays don't hold key value pairs like objects do, so the length isn't incremented when you assign a value. They are however objects themselves, so you can assign values to its properties (in this case the return property).
You probably want params to be a plain object: params = {}
You need to count the properties, like this for example:
function dictionarySize(dict){
var size = 0;
for (key in dict){
// In practice you'd probably want to filter using hasOwnProperty
size++;
}
return size
}
alert(dictionarySize(params));
Or using a library like underscore.js:
_.size(params);
Object.keys is also an option, although it won't work in IE8 and older.
If you don't need an key value pairs use params.push:
params=new Array();
params.push('json')
alert(params.length); // 1
You can create an array, push stuff on it, and assign properties to values of it like so:
var params=[];
params.push('firstly');
params[0]="jonson";
params['return']="fredy"
params.newone="json";
params.push('Carl');
NOW, if you do:
console.log(params.length,params);
the result of that is:
2 ["jonson", "Carl", return: "fredy", newone: "json"]
SO, you see "firstly" was replaced by "jonson" in the [0] - so the "pushed" value is addresed by the numerical [0]
I'm trying to get an array of some images to flip through. The first set need to be in descending order, while the second set need to be in ascending order, so I have written this:
var flipArray = [];
function createFlipArray(older, newer){
flipArray = $("#"+older).children();
flipArray = flipArray.get().reverse();
flipArray = flipArray.push($('#'+newer).children());
console.log(flipArray);
loopThroughImages();
}
When I push the second set onto the first set, it logs the array as 4, even though there are 6 items in the whole array.
If I log the array after I populate it with the older children, it returns with HTML objects, which I expect to see after I push the newer children on.
Any suggestions?
.push modifies the array in-place. It does not return a new array, it returns the array's new length.
Array.prototype.push returns the array's new length. It modifies the original array. Remove the flipArray = before it.
var x = new Array(10);
$.inArray(10,x);
#Returns -1
Fiddle
I've come across this weird issue, checking a value in an array with $.inArray, really simple.
But, if the array only has one value in it, inArray returns -1.
If I add another value to the array, it works as expected.
This only happens with integers and not with strings.
What's going on?!
If you want to create an array with the one number(10) inside you should use bracket literal:
var x = [10];
$.inArray(10,x);
Or with push:
var x = new Array();
x.push(10);
Obviously the first one is more readable and faster to write.
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. Note that this special case only applies to JavaScript arrays created with the Array constructor, not with array literals created with the bracket syntax.
If the only argument passed to the Array constructor is an integer, a new, empty JavaScript array and its length is set to that number
MDN
Fixed fiddle
I suggest to check documentation for arrays in JavaScript, link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
In your case, by using:
var x = new Array(10);
It creates an array with length 10 and each item of the array is undefined
I suggest to use:
var x = [10];
this is an array with one item at index 0 that has value 10.
var x = new Array(10); creates an array with 10 slots, not an array that contains "10"
How to initialize a string array (size<100 items) in javascript whose indexes are scattered over entire integer range, with data items.
If I do like this:
array1 = ["string1","string2","string3","string4"];
then I get array of length 4 with indices ranging 0 to 3
But in my case i want to keep my own indices, so that the array could be used like a high performance int-string hash table.
I'm preferably looking out for a single statement initialization.
The items of the array should be accessible like this: array1[23454]
Update From Comments
I'm restricted to initialize the array as a single statement since a dynamically prepared array initialization string is appended from server side like this: var array = <string from server here>
To create an array with a set number of indexes you can use
// Creates an array with 12 indexes
var myArray = new Array(12);
This isn't needed in javascript due to the way its array's work. There isn't an upper-bound for arrays. If you try to reference an item index in the array that doesn't exist, undefined is returned but no error is thrown
To create an array with perscribed indexes you can use something like array['index'] = value though this would force you to use multiple statements. Javascript doesn't have an array initalizer to allow for you to specify indexes and values all in a single statement though you can create a function to do as such
function indexArray(param) {
var a = [], i;
for (i=0; i<param.length; i+=1) {
a[param[i].index] = param[i].value;
}
return a;
}
var myArray = indexArray([
{ index: 123456, value : "bananas" },
{ index: 12, value : "grapes" },
{ index: 564, value : "monkeys" }
]);
var array1 = []
array1[23454] = 2
Just doing this should be fine. There's no set array size for javascript in the way there is for java.
If you really want to do this all in a single statement, you can make an object instead like this:
var object1 = {
"23454":2,
"123":1,
"50":3
};
and then retrieve the numbers like this:
object1["23454"] //2
I don't really recommend this though. The array method is a cleaner way of doing it even if it takes multiple lines since it doesn't require string conversion. I don't know enough about how these are implemented in browsers to comment on the performance impact.
Update
Since the 1 line requirement is based on something being passed to the server, I would recommend passing a JSON object to the server in the form:
"{"23454":2,"123":1,"50":3}"
then this code will parse it to an object:
var object1 = JSON.parse(jsonstringfromserver);
and if you like you can always convert that to an array by enumerating over the properties with a for in loop:
var array1 = []
for ( num in object1){
array1[num] = object1[num];
That is probably unnecessary though since object1[123] will already return 1. You only need this if you plan on doing array specific operations.
You don't have to pre-define the size of an array before you assign to it. For example:
var _array = [];
_array[0] = "foo";
_array[1000] = "bar"; // _array.length => 1001
_array[1] //undefined
No need to initialise the appropriate number of array elements before you assign to them.
Update
It already has been pointed out that you can use an object rather than an array. However, if you want to take advantage of array methods then this is still possible. Let me give you an example:
var obj = {
0: 15,
1: 10,
2: 5,
length: 3
};
If the object contains a length property then it can be treated as an array-like object. Although you can't call array methods directly from these objects you can use array methods.
Array.prototype.join.call( obj ); // 15,10,5
In fact using the ECMAScript 5 map function you can easily convert the above object to an array.
var _array = Array.prototype.map.call( obj, function( x ) { return x; } );
The map function does not exist in all browsers but you can use the following function if it doesn't.
Array.map = Array.map || function(a, f, thisArg) {
return Array.prototype.map.call(a, f, thisArg);
}
You can do what you want with an Object in this way:
var o = {23454: 'aaaa', 23473: 'bbb'};
You will lose the array methods/fields, e.g. length, but you will gain what you said you are looking for, and you will be able to add/remove members easily.