how do i check if a specific array exists, and if not it will be created?
+2
A:
You can use the typeof
operator to test for undefined and the instanceof
operator to test if it’s an instance of Array:
if (typeof arr == "undefined" || !(arr instanceof Array)) {
var arr = [];
}
Gumbo
2009-12-25 17:19:36
You could use alse instanceof operator.
el.pescado
2009-12-25 17:21:06
To my eye, this is easier to read than Rich's version.
DOK
2009-12-25 17:29:20
I've just become totally obsessed with the "? :" ternary operator as I've been working on code that has large expressions everywhere.
Rich
2009-12-25 17:36:15
A:
If you are talking about a browser environment then all global variables are members of the window object. So to check:
if (window.somearray !== undefined) {
somearray = [];
}
slebetman
2009-12-25 17:21:00
You're right. It wasn't clear from the question if checking that it was an array in advance is necessary, or just checking to see if the variable is already defined. This is a common idiom, and is shorter and simpler than the other ones posted, so I figured I'd post it and let the questioner decide if it's sufficient.
Brian Campbell
2009-12-25 17:47:42
If `arr` is already defined in the relevant scope, then why bother with `var ...`? You can just do `arr = arr || [];`
J-P
2009-12-25 18:15:39
The question was to check whether the array already exists, and create it if not. Thus, you don't know if it's already defined. This idiom is useful if you have several files to be linked together, and don't know which one of them will be loaded first to define some global variable that they will all share.
Brian Campbell
2009-12-25 18:24:26
+8
A:
If you want to check whether an array x exists and create it if it doesn't, you can do
x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []
Rich
2009-12-25 17:21:10
This works in most cases, but it won't cover you if you plan on checking an array instantiated from a different global `Array` constructor - this might occur when scripting across frames.
J-P
2009-12-25 18:17:04
@Rich: See my answer here: http://stackoverflow.com/questions/1961528/javascript-check-if-array-exist-if-not-create-it/1961653#1961653, it will behave correctly on multi-framed DOM environments.
CMS
2009-12-25 21:32:15
+2
A:
If you want to check if the object is already an Array, to avoid the well known issues of the instanceof
operator when working in multi-framed DOM environments, you could use the Object.prototype.toString
method:
arr = Object.prototype.toString.call(arr) == "[object Array]" ? arr : [];
CMS
2009-12-25 18:24:44
The declaration is necessary, but I thought it was pretty obvious that if `arr` is undeclared a `ReferenceError` will be thrown in the right-hand side of the assignment...
CMS
2009-12-26 18:24:03