I want to know if it is possible to declare an array in Javascript of the type "com.peregrine.servicecenter.PWS.Common.MessageType". In java it is easy but in javascript I have not idea. Thanks.
sure it's possible:
var myArray = [];
remember that javascript is not a statically typed language, so you don't need to declare an array of a specific type.... just an array. Now, given the type you're referring to, I don't think that's exactly what you're asking though...
No, it is not possible. The Array in JS doesn't care what you've put in it, or even that the array indexes are numeric. Java, on the other hand, requires strict typing of both. I'd even go so far as to say that even Object[] is a completely different paradigm from [].
You cannot declare an array to exclusively consist of a particular type. However, you can declare an array (var myArray = [];) and you can add objects of your intended type to it (myArray.push(myMessageType);).
You can declare the array in such a way.
var arr = [];
it can contain object or array of object by calling
arr.push(x)
Reference
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Array functions in jQuery
Related
Well, I am not sure if I describe the problem clearly, currently I am using ExtJS to do some developing, I saw some objects are "singleton", such as "Ext.Viewport", In C++, I can get the address of the object to see if they are actually same object, in Python, I can use "id" function to get the hash code of the object, and In Java I have similar built-in function "hashCode" to check if the objects are really same object, is there similar ways in javascript for this? so if there are some functions or operator in javascript, then I can tell if the object in ExtJS defined as "singleton" is really referencing to the same object.
You don't need anything so complicated. If two values are the same object, then they will be equal.
var foo = {};
var bar = foo;
alert(foo == bar);
If they are different (even if identical) objects, they won't be.
var foo = {};
var bar = {};
alert(foo == bar);
Your question is not very clear, but I'll try to answer.
Javascript itself does not use unique identifiers for each object by default. You could add this if you wanted to.
Depending on your requirements, you could also use the typeof operator to compare the type.
ExtJs however, does use unique id's (either id or itemId) and also allows you to get the class name of the object that your using. So you could do this easily in ExtJs.
The answer depends on whether you are comparing the type of object, or the actual object instance itself.
This other SO answer may be beneficial
I think that I'm understanding you... but, did you check this JavaScript comparator ?
=== - equal value and equal type
!== - not equal value or not equal type
reference: Javascript comparators
If you want to know if two object references refer to the same single object instance, use ==.
If you want to do a deep comparison of the referenced objects to see if the objects contain all the same values, even if they are not the same object instance, use Lodash's _.isEqual(a, b) method.
could also convert both to json, and use something like jsonDiff: https://github.com/pkafel/json-diff
I know that Javascript Arrays are actually objects, and because they are objects, they can have properties. Here's an example:
var a = [1, 2, 3];
a.currentIndex = 2;
a.next = function() { ... };
a.prev = function() { ... };
a.length // returns 3
To me this seems like it could come in very handy. I see numerous reasons why you might want to store state or utility functions on the actual array itself and not on some other variable. It even seems better than having the array as a property of an object with the other stuff stored on that object.
Here's my question:
Does anyone know of any issues with storing properties on a Javascript array? Does it work in all browsers? Is there any evidence that this will change with future versions of Javascript? Is there any general wisdom about whether or not it's a good practice?
(p.s. For the record, I don't need to iterate over the array with a for...in loop. I understand that such a loop would include the properties as well)
Since you already ruled out the for in issue, my answer here is a clear "no" - there is no issue to worry about. All Array.prototype methods will only apply on the "indexed" keys (0...n).
The best example here is the well know jQuery library, it also uses Array-Like objects to store DOM nodes on but it also has lots of methods which are attached to that object (jQuery uses the prototype there tho). However, other librarys like Zepto, just put those methods directly on the "array" object itself.
So again, no there is no other caveat and you're save doing it.
Just throwing out one more thing -- None of the "copying" array prototype functions will copy any of your extra properties, if that's important, i.e. .splice, .slice, concat will give you new "clean" arrays without currentIndex, etc
Yes it works in all browsers. And it is valid javascript (arrays are objects). One could think of a number of reasons why you want to use the Array constructor instead of an object, but if this is your preferred coding style, go with it.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
What is the difference between these two methods of defining an array in javascript ?
var arrayList = []
and
var arrayListAgain = new Array();
One is good and the other is bad :-)
No seriously, the first way is shorter (fewer bytes sent over the wire) and it doesn't have any weird potential problems. The second one, however, will work fine.
The weird part with new Array() is this: if you pass one numeric parameter to the constructor, it means "initialize the array so that there are that there are the given number of empty (null) array elements, and so that length is equal to the given number." (Well it has to be an integer, I think actually.) If you pass a single non-number, or two or more numbers, it means, "initialize the array so that its contents reflect this argument list."
Ok now I said there was a weird part, and it's this: if you're using some sort of server side framework, and you want to create an array of numeric values (integer values), like say unique database keys, then you might be tempted to do this:
var keys = new Array(<# favoriteTemplateLanguage.forEach(idList): print(id + ',') #>);
(I made up that syntax of course.) Now what happens if there's just one "id" in your server-side list of keys?
You can use the second one to define an array of a predefined length, e.g.
var arrayListAgain = new Array(20);
will create an array with 20 (undefined) elements.
Also see new Array (len).
none what so ever. Both create a new instance of an Array object.
Douglas Crockford in 'Javascript the good parts' recommends the former method as it is more concise.
They are the same. According to http://www.hunlock.com/blogs/Mastering_Javascript_Arrays:
Current best-practice eschews the
"new" keyword on Javascript
primitives. If you want to create a
new Array simply use brackets [] like
this… var myArray = [];
I recommend reading that page, it contains a lot of useful information about arrays and JS in general.
My JavaScript code stores a lot of data in arrays. I want to retrieve a key using something similar to what I wrote below. It key that should be retrieved is based on variables that are page-dependent . The following code doesn't work. Can anyone give me a solution to this problem?
This is part of a script that does automatic conjugation. (looks for SUBJECT in a div and then looks for VERB in another div and then conjugates the verb by retrieving the conjugated form from the array)
function getarray(Array,Key) {
return Array[Key];
}
Example of how it should work:
verb = innerhtmlfromdiv;
subject = innerhtmlfromotherdiv;
function getarray(Array,Key) {
return Array[Key]; }
conjugatedverb = getarray(verb,subject);
htmltextbox.value = conjugatedverb;
First off, what you want is an Object, not an Array. I'm guessing that you're new to javascript and your previous language was either PHP or PERL, and so you think what you're using is an "Associative Array".
The basics: There is no such thing as Associative arrays in Javascript. There is Objects, and a non-primitive subclass of Object called Array, which has some methods for dealing with Numericly named object properties, and a magic length property.
Since the keys you are dealing with are strings, not numbers, you have no use for Arrays.
Javascript Objects on the other hand are similar to an Associative array in php, or a hash in perl. (but they are not exactly the same thing).
As you have no doubt discovered, with an Object, you can use subscript notation to access certain properties, as in
verbs["go"] = "went";
this is equivilent to
verbs.go = "went";
a common mistake is to think that the dot notation is only used for objects, and the subscript notation for "associative arrays", because this is how it works in PHP. In javascript the two notations are interchangable. Since Arrays are a subclass of Object, the above examples work on them as well (but they don't use any special properties of Arrays).
As for your specific problem:
You need an object full of objects.
so for instance
var verbs = {
"do":{"Truck":"Drive","Blender":"Turn On","Bike":"Ride"},
"take":{"Money":"Steal","Julie":"Accompany","Lever":"Pull}
}
then your function would be:
function conjugate (verb, subject) {
return verbs[verb][subject];
}
and an example of its use would be
conjugate("do","Truck") // returns "Drive"
Try changing the parameter name Array to something else. Array is the name of a built-in function/object in javascript.
I don't quite get the point of the function. This is like writing:
function getValue(var) {return var}
Why not just get the value the normal way without wrapping it in a useless function:
conjugatedverb = verb[subject];
htmltextbox.value = conjugatedverb;
Also, your code doesn't make sense when you claim to do an innerHTML from an element and somehow get an object instead of a string. What is really going on? I think your problem starts even before this snippet of code.
Can someone tell me what exactly the two above lines of javascript do? And more importantly, what it's called so I can search some javascript references to learn about it? I assume they are both creating some form of an array that objects can be added to...?
Curly braces are syntax for creating a Javascript object (which is really a glorified collection of key/value pairs); the brackets make a resizable array.
These are called literals, and they're a handy shortcut to help you make objects and arrays without a lot of typing (good, because you use them all the time). Many other programming languages have similar literal syntax for maps and arrays.
It creates an empty dictionary in map and an empty array in list.
Read up on these structures at http://www.geocities.com/schools_ring/ArrayAndHash.html.