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.
Related
Coming from the C# world, I'm used to doing something like
var names = persons.select(x=>x.name);
I now want to do a similar thing in CoffeeScript. I have an array of objects and I want to extract a field from each object and put it into an array. I'm sure I can do this using lambdas, I'm just unsure of how the syntax would work out.
No use of lambdas unless you use the native Array map method (equvivalent to C#'s select):
names = persons.map((x) -> x.name)
However, the common CoffeeScript idiom for this is to use a for-loop as an array comprehension:
names = (x.name for x in persons)
I've been following Backbone Collection's convention of having arrays of data objects and using _.find/findWhere etc to loop through the array, even when I wasn't using Backbone. However it seems like it would be more efficient to instead store them as an associative array with the id as keys if I know that they will be unique. Are there any pitfalls to this that I'm not seeing?
So basically:
var map = {};
map["someId"] = someObject;
map["someOtherId"] = someOtherObject;
// ...later to get the object:
var o = map["someId"];
If so, then the answer to "are there any pitfalls...I'm not seeing" is "no": Looking up properties on objects is a very common operation, which JavaScript engines do very quickly.
In fact, since normal JavaScript arrays aren't really arrays at all, it's markedly more efficient to look things up this way rather than storing them in arrays and using forEach or similar to find them. Every time you get an entry from an array (e.g., a[0] or whatever), that's a property access operation, just like looking up a property in an object. (In fact, that's exactly what it is, barring the JavaScript engine knowing it can optimize the operation.) Getting an element from one of the new typed arrays is faster because they really are arrays (although searching through them will still be non-trivial), but getting an element from a standard array is a property lookup on an object, so you might as well just do one lookup (on your map, using your key) instead.
(Side note: In JavaScript, the term "associative array" isn't usually used. It's just an object. Sometimes you also hear "map".)
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
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.