I have some js arrays and I want to find the arrays by name. for example:
arr1 = [1,2,3];
arr2 = [3,4,5];
And access them like this:
var intNum = 2;
var arrName = 'arr' + intNum;
arrName[0]; // equals 3
Is this possible?
Thanks,
Kevin
It is possible but I would suggest you place these arrays as properties of an object, that makes it a lot easier
var arrays {
arr1 : [1,2,3],
arr2 : [4,5,6]
}
var arrNum = 2;
var arr = arrays["arr" + arrNum] // arrays.arr2
Properties of objects can be accessed both using the . operator and as named items using the ["propname"] notation.
Using eval or resorting to using the above trick on window is not advised.
Eval'ing is normally a sign of ill constructed code, and using window relies on window being the Variable Object of the global scope - this is not part of any spec and will not necessarily work across browsers.
window['arr'+intNum]
so
arr1 = [1,2,3];
arr2 = [3,4,5];
intNum=2;
alert(window['arr'+intNum][1]); //will alert 4
Related
In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
I have a code :
var index = 100;
var arr =[];
arr[index.toString()] = "Hello"
The result : index still known as integer not a string. Anyone can explain what's wrong with my code?
You have to declare associative arrays using {}, which creates a new object, because in JavaScript, arrays always use numbered indexes.
You need to declare an object: var arr={};
arrays use numbered indexes.
objects use named indexes.
var index = 100;
var arr ={};
arr[index.toString()] = "Hello";
console.log(arr);
How to make associative array with number as string in Javascript
JavaScript doesn't have associative arrays in the sense that term is frequently used. It has objects, and as of ES2015 (aka "ES6"), it has Maps.
The result : index still known as integer not a string. Anyone can explain what's wrong with my code?
The index variable's value is still a number, yes, because you haven't done anything to change it. But the index in the array is a string (and would be even if you didn't use .toString()), because standard arrays aren't really arrays at all1, they're objects with special handling of a class of properties (ones whose names are strings that fit the spec's definition of an array index), a special length property, and that use Array.prototype as their prototype.
Here's proof that array indexes are strings:
var a = [];
a[0] = "zero";
for (var name in a) {
console.log("name == " + name + ", typeof name == " + typeof name);
}
That said, you don't want to use an array when you want a generic object or map.
Here's using a generic object for name/value mappings:
var o = Object.create(null);
var name = "answer";
o[name] = 42;
console.log(o[name]); // 42
The property names in objects are strings or (as of ES2015) Symbols. I used Object.create(null) to create the object so it wouldn't have Object.prototype as its prototype, since that gives us properties (toString, valueOf, etc.) that we don't want if we're using the object as a map.
Here's using a Map:
var m = new Map();
var name = "answer";
m.set(name, 42);
console.log(m.get(name)); // 42
The main advantages Maps have over objects are:
Their keys can be anything, not just strings or Symbols
They're iterable, so you can use for-of to loop through the mappings they contain
Maps have a size property telling you how many entries they have
Maps guarantee that iteration of their entries is performed in the order the entries were added to the map
With ES6, you could use a Map, which holds any type as key.
var map = new Map;
map.set(100, "Hello");
map.set('100', "Foo");
console.log(map.get(100)); // 'Hello'
console.log(map.get('100')); // 'Foo'
console.log([...map]);
JavaScript does not support arrays with named indexes, in JavaScript, arrays always use numbered indexes.
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
As you can see in the following example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
console.log(x);
var y = person[0]; // person[0] will return undefined
console.log(y);
Note: this isn't one of the millions dups of the common array copy 'problem' where using arr.slice(0) fixes this 'problem'
That said, I want to understand why I am getting this unexpected result:
var oldArr = [[1,2],[3,4]];
var find = oldArr[1];
var newArr = oldArr.slice(0);
console.log(newArr.indexOf(find)); //1?
//proof that newArr is NOT referenced to oldArr
newArr[0] = "Hi";
newArr[1] = "How are you?";
console.log(oldArr+" "+newArr); //"1,2,3,4 Hi,How are you?"
jsFildde Demo
If you replace find with any of the following alternatives, it returns the expected -1:
Use [3,4] directly
Use a variable holding [3,4]
Use a variable with reference of another array holding [3,4]
I can't find any explanation on why there is any difference between these last three methods and the first example. As far as I know, there shouldn't be any.
Any ideas?
In:
[[1,2],[3,4]]
There are three array objects created.
Only the outer one is being slice'd. This results in a "shallow copy".
Consider this:
var a = [1,2]
var b = [3,4]
var c = [a,b]
var d = c.slice(0)
d[0] === a // true, which means it is the /same/ object
d[0][0] = "Hi!"
a // ["Hi!", 2]
Happy coding!
Everything is working as expected
indexOf searches by reference and not value, therefore if two objects do not === each other, indexOf will not find them
In your case:
var oldArr = [[1,2],[3,4]];
var find = oldArr[1];
var newArr = oldArr.slice(0);
find points to the array [3,4];
so newArray contains 2 objects (the two arrays).
If you want to see what is really going on try doing find.push(5)
In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
Can some one explain the conceptual difference between both of them. Read somewhere that the second one creates a new array by destroying all references to the existing array and the .length=0 just empties the array. But it didn't work in my case
//Declaration
var arr = new Array();
The below one is the looping code that executes again and again.
$("#dummy").load("something.php",function(){
arr.length =0;// expected to empty the array
$("div").each(function(){
arr = arr + $(this).html();
});
});
But if I replace the code with arr =[] in place of arr.length=0 it works fine. Can anyone explain what's happening here.
foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.
foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.
Read somewhere that the second one creates a new array by destroying all references to the existing array
That is backwards. It creates a new array and doesn't destroy other references.
var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);
gives:
[] [] [1, 2, 3] []
arr.length =0;// expected to empty the array
and it does empty the array, at least the first time. After the first time you do this:
arr = arr + $(this).html();
… which overwrites the array with a string.
The length property of a string is read-only, so assigning 0 to it has no effect.
The difference here is best demonstrated in the following example:
var arrayA = [1,2,3,4,5];
function clearUsingLength (ar) {
ar.length = 0;
}
function clearByOverwriting(ar) {
ar = [];
}
alert("Original Length: " + arrayA.length);
clearByOverwriting(arrayA);
alert("After Overwriting: " + arrayA.length);
clearUsingLength(arrayA);
alert("After Using Length: " + arrayA.length);
Of which a live demo can be seen here: http://www.jsfiddle.net/8Yn7e/
When you set a variable that points to an existing array to point to a new array, all you are doing is breaking the link the variable has to that original array.
When you use array.length = 0 (and other methods like array.splice(0, array.length) for instance), you are actually emptying the original array.
Are you sure it really works?
I did a little experiment here, and trying to "add" an Array with a String resulted in a string.
function xyz(){
var a = [];
alert(typeof(a+$("#first").html()));
// shows "string"
}
http://www.jsfiddle.net/4nKCF/
(tested in Opera 11)