How to get the correct array length - javascript

In my code i initialize array then put a value inside it why the output be 0 ?in spite of this should be 1
var changedfields=[];
changedfields['product']="productname";
alert(changedfields.length);

You're creating an associative array (normal arrays have an numeric index) but are actually trying to build a HashMap (a key, value pair). Use Objects or ES6 Maps.
I hope the following example will help you out:
var changedfields = {}; // create an object
changedfields['product']="productname";
var keys = Object.keys(changedfields); // returns the keys of the object ['product']
alert(keys.length);
I would suggest to read more about datastructures in javascript and avoid associative arrays in general.
Length of a JavaScript object (that is, associative array)
associative array versus object in javascript

Your question is interesting. Following is the answer.
First of all Arrays in Javascript are object type.
The first line you wrote creates an empty array and it's type is object.
var changedfields=[];
The second line you wrote creates a property called product of changedfields and sets the value to productname. It allows you add the product property because Javascript Array type is object. If you just had var changedfields; you could not add this property.
changedfields['product']="productname";
The third line you wrote simply finds the length of the empty array.
alert(changedfields.length);
In Javascript associative arrays are achieved using object. But if you want to add the product name in changedfields array. You could use push method like below and check the length:
changedfields.push('productname');
console.log(changedfields.length);
Javascript numerical indexed array length
So the Javascript numerical indexed array length can be calculated this way:
console.log(array.length);
console.log(changedfields.length); // in your case
The Javascript associative array length
The Javascript associative array (object) length can be calculated following ways:
Option 1:
Object.len = function(obj) {
var objLen = 0;
for (i in obj) {
obj.hasOwnProperty(i) ? objLen++ : '';
}
return objLen;
};
console.log(Object.len(changedfields));
Option 2:
console.log(Object.keys(array).length);
console.log(Object.keys(changedfields).length); // in your case
Note: This has issues with Internet Explorer 8, Opera etc

Related

NodeJS: Array automatically gets converted into object? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: Check if object is array?
Why is an array of objects considered an object, and not an array? For example:
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json',
data: { screen_name: 'mick__romney'},
dataType: 'jsonp',
success: function(data) {
console.dir(data); //Array[20]
alert(typeof data); //Object
}
});​
Fiddle
One of the weird behaviour and spec in Javascript is the typeof Array is Object.
You can check if the variable is an array in couple of ways:
var isArr = data instanceof Array;
var isArr = Array.isArray(data);
But the most reliable way is:
isArr = Object.prototype.toString.call(data) == '[object Array]';
Since you tagged your question with jQuery, you can use jQuery isArray function:
var isArr = $.isArray(data);
Quoting the spec
15.4 Array Objects
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. 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; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
Primitive Data types - This includes null, undefined, string, boolean, number and object.
Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Length - This can be 0 or above (non-negative).
The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.
Hope this helped shed more light on why typeof Array returns an object. Cheers!
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that

Javascript create 2d Array with ids as array key

I need an array structure that includes the user id as array key and can store more information about that user (2 dimensional array). In my case if he is allowed to perform database requests, these are represented by request id and true/false.
Each user can have multiple requests
For example:
User id =14 and requests ids =22 and true and 45 and false
User id =12 and requests ids =44 and false and 77 and false
It should look like this:
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
I’m struggling with js syntax since
var id[14] ;
Creates an array with 14 elements and the rest of the array is empty but I want an array where at the 14 position all my requests information are stored.
You can use the [] syntax with regular JS objects like the one you describe. Simple example:
var ob = {10: {11:true}, 12: {13: false}};
console.log(ob[10]); //Displays the object {11:true}
console.log(ob[10][11]); //Displays true
If you create the array first, then assign the values you will edit only the nth element e.g.
var id = [];
id[14] = 'xyz'
Gives an array with 14 undefined's and 'xyz' as the 15th element.
It sounds as though you don't want an array at all, you want an object with object values for its properties (or if you're using ES2015, a Map of Maps).
Your
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
(which is perfectly valid syntax, other than you should have a ; at the end) gives you the former: You index into it with the user ID (14) and then index into the object you get as a result with the request IDs (22 and/or 45), which gives you a boolean value.
You create an object like this:
var users_rights = {};
You add a property to it for the key 14 like this:
users_rights[14] = {};
You add properties to that the same way:
users_rights[14][22] = true;
users_rights[14][45] = false;
These objects are just plain objects, not arrays. Brackets notation works with them just fine (in fact, it's the fact that brackets notation works with objects that makes it work with arrays, because standard arrays in JavaScript aren't really arrays at all).

Empty Array in javascript

I created an object which contains an array.
I noticed that when I dont enter any values into the array, it still has one - its size,
So how can I check if the array is actually empty?
Here's how I'm creating the array:
array = { text:[10] }
The size of the array is not an array entry (aka array "element"). It is a property, length, but it's not an entry. An empty array is exactly that: empty.
The code you posted in a comment:
array = { text:[10] }
does not create an empty array. It creates an array of length 1 with the entry 10 in it.
If you want to create an empty array with a specific length, you can't do that in a single statement with an array literal ([]). You have two ways you can do it:
Using an array literal and assigning to length:
var a = [];
a.length = 10;
or using new Array:
var a = new Array(10);
But there's virtually never any reason, in JavaScript, to predefine the length of the array, because standard JavaScript arrays aren't really arrays at all. It does make sense with the new typed arrays (Uint32Array and such), and to do it you have to use the array constructor (new Uint32Array(10)).

javascript array indexing with large integers

I have a strange problem. I need a multidimensional javascript array that has numeric indexes e.g.:
MyArray = new Array();
$(".list-ui-wrapper").each(function(){
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
MyArray ["'"+unique+"'"] = new Array();
});
The unique is a 8 digit integer. So if I dont wrap it inside the quotes, the ListUI_col_orders array will become extremly big, because if the unique = 85481726 then javascript will fill the array with 85481725 undefined elements before the the new empty array at the 85481726th index.
My problem is that later if i generate the unique again i cannot access the array anymore:
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
console.log(MyArray [unique]); // undefined
console.log(MyArray ['"'+unique+'"']); // undefined
console.log(MyArray [unique.toString()]); // undefined
Any tips?
If you are going to use an array that's mostly sparse, then use a Hash table instead.
eg, set your variable as follows:
ListUI_col_Orders = {};
Then your indexing will be a key, so you don't have to worry about all the interstitial elements taking up space.
...because if the unique = 85481726 then javascript will fill the array with 85481725 undefined elements before the the new empty array at the 85481726th index.
No, it won't. JavaScript standard arrays are sparse. Setting an element at index 85481725 results in an array with one entry, and a length value of 85481726. That's all it does. More: A myth of arrays
The problem is that you're trying to retrieve the information with a different key than the key you used to store it. When storing, you're using a key with single quotes in it (actually in the key), on this line of code:
MyArray ["'"+unique+"'"] = new Array();
Say unique is 85481726. That line then is equivalent to this:
MyArray ["'85481726'"] = new Array();
Note that the key you're using (the text between the double quotes) has ' at the beginning and end. The actual property name has those quotes in it. Since it doesn't fit the definition of an array index, it doesn't affect length. It's a non-index object property. (How can you add a property to an array that isn't an array index? Arrays are not really arrays, see the link above.)
Later, you never use that key when trying to retrieve the value:
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
console.log(MyArray [unique]); // undefined
console.log(MyArray ['"'+unique+'"']); // undefined
console.log(MyArray [unique.toString()]); // undefined
The keys you tried there were 85481726, "85481726" (with double quotes), and 85481726 again. Note that you never tried '85481726' (with single quotes), which is the key you used originally. Since you didn't use the same key, you didn't get the value.
Either use consistent quotes, or (much better) don't use quotes at all. Don't worry about the array length being a large number, JavaScript arrays are inherently sparse. Adding an entry with a large index does not create several thousand undefined entries in front of it.
All of that being said, unless you need the "array-ness" of arrays, you can just use an object instead. Arrays are useful if you use their features; if you're not using their array features, just use an object.
More about the sparseness of arrays: Consider this code:
var a = [];
a[9] = "testing";
console.log(a.length); // 10
Although the length property is 10, the array has only one entry in it, at index 9. This is not just sophistry, it's the actual, technical truth. You can tell using in or hasOwnProperty:
console.log(a.hasOwnProperty(3)); // false
console.log("3" in a); // false
When you try to retrieve an array element that doesn't exist, the result of that retrieval is undefined. But that doesn't mean there's an element there; there isn't. Just that trying to retrieve an element that doesn't exist returns undefined. You get the same thing if you try to retrieve any other property the object doesn't have:
var a = [];
a[9] = "testing";
console.log(a[0]); // undefined
console.log(a[200]); // undefined
console.log(a["foo"]); // undefined
Final note: All of this is true of the standard arrays created with [] or new Array(). In the next spec, JavaScript is gaining true arrays, created with constructors like Int32Array and such. Those are real arrays. (Many engines already have them.)

Trouble with basic Javascript

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]

Categories