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.
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 years ago.
Closely related questions:
associative array versus object in javascript
Why does JavaScript not throw an exception for this code sample?
javascript array associative AND indexed?
I have the following code sample:
var someVariable = {abc: "def", ghi: "jkl"}
someVariable["SomeProperty"] = "dfsdfadsd"
alert(someVariable["SomeProperty"])
var someOtherVariable = { abcd: "defsd", ghij: "dfsdfdss" }
someOtherVariable.SomeOtherProperty = "adfsdfsd"
alert(someOtherVariable.SomeOtherProperty);
alert(someOtherVariable["SomeOtherProperty"])
All of them do exactly what they look like - they attach a property to their respective objects. The alert shows the expected string in every case. My understanding from the related questions is that there's no functional difference between the two.
I also encountered the following statements in W3Schools's JavaScript arrays tutorial:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
If that's the case, why is array syntax permitted here at all? (Again, my understanding from the related questions is that the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood").
As far as I know (and please correct me if I'm wrong as JavaScript isn't my primary language), it's not possible to do other things you'd expect to be able to do with an array (e.g. iteration with a for loop), so why bother having both syntaxes? In C# you can do something like:
// A C# dictionary is basically an associative array
Dictionary<string, int> dict = new Dictionary<string, int>();
// Fill dictionary ...
foreach (string key in dict.Keys) {
int value = dict[key];
// Do something with the value
}
but I'm not aware of a way to do a similar thing with JavaScript properties. There's a clear necessity for this syntax in C# (keys are definitely not properties of dict), but why does JavaScript have this (given that they're exactly equivalent)? Am I missing something, or is this actually completely redundant?
Why does JavaScript allow array syntax to access properties?
It isn't "array syntax".
Square brackets are a standard way to access the properties of an object.
Arrays are just a type of object.
Square bracket notation has some advantages over dot notation for accessing properties:
You can use any expression to define the name, including variables and function calls.
You can access properties which have names that are invalid in an identifier (such as those which start with a number, which is why you commonly see them used to access arrays).
It's also more verbose and potentially less efficient.
the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood"
JavaScript doesn't have a feature called "associative arrays". (W3Schools is not a trustworthy source).
It has objects, which are (at their core) collections of property:value pairs. (This is similar to PHP's associative array feature).
It has arrays, which are objects which inherit from the Array constructor, gaining methods like forEach and properties like length (which uses a getter function to determine its value based on the properties with a name that is the highest integer value).
This question already has answers here:
trying to convert a letter to uppercase using .toUpperCase()... doesn't work?
(2 answers)
Closed 6 years ago.
I writing a small program that takes the English and the Spanish version of a word from two user inputs and stores them as objects:
function Dictionary(english, foreign){
this.english = english;
this.foreign = foreign;
}
Thes objects are then stored in an array; objectsArray[].
I then assign a method to the "Dictionary" prototype to make the inputted strings into uppercase:
Dictionary.prototype.capMethod = function(){
this.english.toUpperCase();
this.foreign.toUpperCase();
}
Once the user has then inputted all the translations (which they will later be tested on), I try to call the dictionaries' capMethod:
for(var x in objectsArray){
objectsArray[x].capMethod();
console.log(objectsArray[x].english + objectsArray[x].foreign + typeof objectsArray[x].english); }
The console, however, does not suggest they have been changed to uppercase. This is corroborated when the english and foreign values are returned to the user (later in the program) still as they were inputted.
I stress that there are other parts of the program where I could make this change but not understanding my mistake here seems like a poor reason to do it another way.
I do need to capitalise the strings that are stored in the dictionaries and there is ALOT of code around it so a JSfiddle would be cumbersome, I hope the above will be enough as the problem really seems to lie in the way I'm referencing the objects values. I also know there are several subtly different ways to reference object properties but I'm new to javascript and am struggling to wrap my head around it.
What am I doing wrong here?
in your function
Dictionary.prototype.capMethod = function(){
this.english.toUpperCase();
this.foreign.toUpperCase();
}
the result of the 'toUpperCase()' is not used.
this.english = this.english.toUpperCase();
would be better.
Would storing objects like this work for you?:
function store(english,foreign){
objectsArray.push({
english:english.toUpperCase(),
foreign:foreign.toUpperCase())
}
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
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.