Arrays in Javascript - javascript

I always had this silly doubt in mind but never had come up with the solution.
I have seen several kind of arrays but I don't know the difference between them. I don't know how to explain exactly but it's most when passing parameters with jQuery.
See:
{ 'choices[]': ["Jon", "Susan"] } in $("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
What's the {}? (does this mean it's an array?). Why is choices[] quoted? I have already seen unquoted ones, what's the difference? I presume that choices is the associative name and ["Jon", "Susan"] is the value, is it right?

The braces { } will construct an object using the object literal notation. You are not constructing an array, but an object, even though JavaScript objects can also be thought of as associative arrays.
Further reading:
Douglas Crockford: A Survey of the JavaScript Programming Language (scroll to the Objects section)
Apart from the few primitive types (numbers, strings, booleans, null and undefined) everything is an object in JavaScript (even functions).
Objects are basically containers of properties, which happen to be very useful for collecting and organizing data.
The object literal notation (the braces { } method that you describe) is very handy for creating objects:
var myFirstObject = {
'name': 'Bobby',
'surname': 'Smith'
};
The quotes around property names are optional if the name would be a legal JavaScript identifier and not a reserved word. That is why 'choices[]' is quoted in your example, because it is not a legal JavaScript identifier. A property's name can be any string as long as it is quoted.
Objects can also contain other objects, so they can easily represent trees or graphs:
var myFlight = {
'airline': 'Airline Name',
'number': 'AN700',
'departure': {
'IATA': 'SYD',
'time': '2010-09-04 23:10:00'
},
'arrival': {
'IATA': 'LAX',
'time': '2010-09-05 05:14:00'
}
};
JavaScript objects also happen to be a convenient hash table data structure, and can be used as associative arrays as mentioned earlier. You could easily do the following:
var myHashTable = {};
myHashTable['name'] = 'Bobby';
myHashTable['surname'] = 'Smith';
// subscript notation:
alert(myHashTable['name'] + ' ' + myHashTable['surname']);
// dot notation: (equivalent)
alert(myHashTable.name + ' ' + myHashTable.surname);

{} are for javascript objects aka JSON notation. [] are for arrays.
{attributeName1: 'attributeValue1', attributeName2: 'attributeValue2'}
vs
['arrayValue1', 'arrayValue2']

{} is the syntax for creating an object. [] is the syntax for creating an array. Objects are collections of items in the format key->value; arrays are collections of items with the value stored only.
'choices[]' is quoted because choices[] (without the quotes) would have a special meaning in Javascript. By quoting it, it is treated as a string and is therefore allowed to be the key in the object. You only need to quote object keys where they would otherwise have a special meaning in Javascript.

JavaScript has arrays and objects (which can be considered associative arrays). An object looks like this:
var someObject = {
'key': 'value',
'anotherKey': 'anotherValue'
};
And an array looks like this:
var someArray = [
'value',
'anotherValue'
];
An array is technically a subClass of Object whose keys are zero-indexed numbers though creating on object with numbers as keys will not give you an array. (Its also a syntax error because keys must be strings)
{1: 'foo'} != ['foo']
{'1': 'foo'} != ['foo']

Related

what is the main difference between JS object and JSON? [duplicate]

Can someone tell me what is the main difference between a JavaScript object defined by using Object Literal Notation and JSON object?
According to a JavaScript book it says this is an object defined by using Object Notation:
var anObject = {
property1 : true,
showMessage : function (msg) { alert(msg) }
};
Why isn't it a JSON object in this case? Just because it is not defined by using quotation marks?
Lets clarify first what JSON actually is. JSON is a textual, language-independent data-exchange format, much like XML, CSV or YAML.
Data can be stored in many ways, but if it should be stored in a text file and be readable by a computer, it needs to follow some structure. JSON is one of the many formats that define such a structure.
Such formats are typically language-independent, meaning they can be processed by Java, Python, JavaScript, PHP, you name it.
In contrast, JavaScript is a programming language. Of course JavaScript also provides a way to define/describe data, but the syntax is very specific to JavaScript.
As a counter example, Python has the concept of tuples, their syntax is (x, y). JavaScript doesn't have something like this.
Lets look at the syntactical differences between JSON and JavaScript object literals.
JSON has the following syntactical constraints:
Object keys must be strings (i.e. a character sequence enclosed in double quotes ").
The values can be either:
a string
a number
an (JSON) object
an array
true
false
null
Duplicate keys ({"foo":"bar","foo":"baz"}) produce undefined, implementation-specific results; the JSON specification specifically does not define their semantics
In JavaScript, object literals can have
String literals, number literals or identifier names as keys (since ES6, keys can now also be computed, which introduces yet another syntax).
The values can be any valid JavaScript expression, including function definitions and undefined.
Duplicate keys produce defined, specified results (in loose mode, the latter definition replaces the former; in strict mode, it's an error).
Knowing that, just by looking at the syntax, your example is not JSON because of two reasons:
Your keys are not strings (literals). They are identifier names.
You cannot assign a function as a value to a "JSON object" (because JSON doesn't define any syntax for functions).
But most importantly, to repeat my explanation from the beginning: You are in a JavaScript context. You define a JavaScript object. If any, a "JSON object" can only be contained in a string:
var obj = {foo: 42}; // creates a JavaScript object (this is *not* JSON)
var json = '{"foo": 452}'; // creates a string containing JSON
That is, if you're writing JavaScript source code, and not dealing with a string, you're not dealing with JSON. Maybe you received the data as JSON (e.g., via ajax or reading from a file), but once you or a library you're using has parsed it, it's not JSON anymore.
Only because object literals and JSON look similar, it does not mean that you can name them interchangeably. See also There's no such thing as a "JSON Object".
JSON has a much more limited syntax including:
Key values must be quoted
Strings must be quoted with " and not '
You have a more limited range of values (e.g. no functions allowed)
There is really no such thing as a "JSON Object".
The JSON spec is a syntax for encoding data as a string. What people call a "JSON Object" ( in javascript ) is really just an ordinary javascript object that has (probably) been de-serialized from a valid JSON string, and can be easily re-serialized as a valid JSON string. This generally means that it contains only data ( and not functions ). It also means that there are no dates, because JSON does not have a date type ( probably the most painful thing about JSON ;)
Furthermore, (side-rant...) when people talk about a "JSON Object", they almost always mean data that has the "curly-braces" at the top-level. This corresponds nicely to a javascript object. However, the JSON spec does not require that there be a single "curly-braces" object at the top-level of a JSON string. It is perfectly valid JSON to have a list at the top-level, or even to have just a single value. So, while every "JSON Object" corresponds to valid JSON, not all valid JSON strings correspond to what we would call a "JSON Object"! ( because the string could represent a list or an atomic value )
According to JSON in JavaScript,
JSON is a subset of the object
literal notation of JavaScript.
In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around.
In addition to reading the documentation, as #Filix King suggested, I also suggest playing around with the JSONLint online JSON validator. That's how I learned that the keys of JSON objects must be strings.
🔫 JSON: The Fat-Free Alternative to XML
JSON has been widely adopted by people who found that it made it a lot easier to produce distributed applications and services. The official Internet media type for JSON is application/json RFC 4627. JSON filenames use the extension .json.
â–º JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. JSON has been used to exchange data between applications written in any Programming language.
The JSON object is a single object that contains two functions, parse and stringify, that are used to parse and construct JSON texts.
JSON.stringify produces a String that conforms to the following JSON grammar.
JSON.parse accepts a String that conforms to the JSON grammar.
The parseJSON method will be included in the Fourth Edition of ECMAScript. In the meantime, a JavaScript implementation is available at json.org.
var objLiteral = {foo: 42}; // JavaScript Object
console.log('Object Literal : ', objLiteral ); // Object {foo: 42}foo: 42__proto__: Object
// This is a JSON String, like what you'd get back from an AJAX request.
var jsonString = '{"foo": 452}';
console.log('JOSN String : ', jsonString ); // {"foo": 452}
// This is how you deserialize that JSON String into an Object.
var serverResposnceObject = JSON.parse( jsonString );
console.log('Converting Ajax response to JavaScript Object : ', serverResposnceObject); // Object {foo: 42}foo: 42 __proto__: Object
// And this is how you serialize an Object into a JSON String.
var serverRequestJSON = JSON.stringify( objLiteral );
console.log('Reqesting server with JSON Data : ', serverRequestJSON); // '{"foo": 452}'
JSON is subset of JavaScript. Javascript was derived from the ECMAScript Programming Language Standard.
â–º ECMAScript
ECMAScript has grown to be one of the world's most widely used general purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications. ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape Communications)) and JScript (Microsoft Corporation).). Though before 1994, ECMA was known as "European Computer Manufacturers Association", after 1994, when the organization became global, the "trademark" "Ecma" was kept for historical reasons.
ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript are called "Dialects".
Dialects have been derived from the same language. They are are quite similar to each other as they have been derived from the same language but they have undergone some changes.
A dialect is a variation in the language itself. It is derived from a single language.
SQL Language - Hibernate MySQL Dialect, Oracle Dialect,.. which have some changes or added functionality.
Information about the browser and computer of your users.
navigator.appName // "Netscape"
ECMAScript is the scripting language that forms the basis of JavaScript. JavaScript language resources.
ECMA-262 Links
Initial Edition, June 1997
PDF.
2nd Edition, August 1998
PDF.
3rd Edition, December 1999 PDF.
5th Edition, December 2009 PDF.
5.1 Edition, June 2011 HTML.
6th Edition, June 2015 HTML.
7áµ—Ê° Edition, June 2016 HTML.
8th edition, June 2017 HTML.
9th Edition, 2018 HTML.
NOTE « 4th edition of ECMAScript not published as the work was incomplete.
JSON defines a small set of formatting rules for the portable representation of structured data.
â–º Key values must be quoted, only Strings are allowed for keys. If you use other than String it will convert to String. But not recommended to use keys other than String's. Check an example like this - { 'key':'val' } over RFC 4627 - jsonformatter
var storage = {
0 : null,
1 : "Hello"
};
console.log( storage[1] ); // Hello
console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
var objLiteral = {'key1':'val1'};
var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
var obj = { k: 'v' }, obj2 = { k2: 'v2' };
var fun = function keyFun() {} ;
objLiteral[ arr ] = 'ArrayVal'; objLiteral[ arr2 ] = 'OverridenArrayVal';
objLiteral[ obj ] = 'ObjectVal'; objLiteral[ obj2 ] = 'OverridenObjectVal';
objLiteral[ fun ] = 'FunctionVal';
console.log( objLiteral );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log( JSON.stringify( objLiteral ) );
// {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log('Accessing Array Val : ', objLiteral[ [10,20] ] );
console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
â–º JSON Strings must be quoted with " and not '. A string is very much like a C or Java string. Strings should be wrapped in double quotes.
Literals are fixed values, not variables, that you literally provide in your script.
A string is a sequence of zero or more characters wrapped in quotes with backslash escapement, the same notation used in most programming languages.
🔫 - Special Symbols are allowed in String but not recomended to use.
" - Special characters can be escaped. But not recomended to escape (') Single Quotes.
In Strict mode it will throw and Error - SyntaxError: Unexpected token ' in JSON
Check with this code { "Hai\" \n Team 🔫":5, "Bye \'": 7 } over online JSON Edtions. Modes notStrict, Strinct.
var jsonString = "{'foo': 452}"; // {'foo': 452}
var jsonStr = '{"foo": 452}'; // {"foo": 452}
JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
JSON.parse( jsonStr ); // Object {foo: 452}
objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
objLiteral.key2 = 'val';
// objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key↵3": "val"}
JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
Object Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
â–º You have a more limited range of values (e.g. no functions allowed). A value can be a string in double quotes, number, boolean, null, object, or array. These structures can be nested.
var objLiteral = {};
objLiteral.funKey = function sayHello() {
console.log('Object Key with function as value - Its outcome message.');
};
objLiteral['Key'] = 'Val';
console.log('Object Literal Fun : ', objLiteral );
// Object Literal Fun : Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
â–º JavaScript is the most popular implementation of the ECMAScript Standard.
The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.
JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
Literals :
'37' - 7 // 30
'37' + 7 // "377"
+'37' + 7 // 44
+'37' // 37
'37' // "37"
parseInt('37'); // 37
parseInt('3.7'); // 3
parseFloat(3.7); // 3.7
// An alternative method of retrieving a number from a string is with the + (unary plus) operator:
+'3.7' // 3.7
Object literals RFC 7159
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s
prototype) associated with its constructor. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.
A prototype is an object used to implement structure, state, and behavior inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor’s associated prototype for the purpose of resolving property references. The constructor’s associated prototype can
be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.
As far as I understand the main difference is the flexibility.
JSON is a kind of wrapper on "JavaScript Object Notation" which forces users to obey more strict rules for defining the objects. And it does this by limiting the possible object declaration ways provided by JavaScript Object Notation feature.
As a result we have a simpler and more standardized objects which suits better on data-exchange between platforms.
So basically, the newObject in my example above is an object defined by using JavaScript Objeect Notation; but it is not a 'valid' JSON object because it does not follow the rules that JSON standards require.
This link is also quite helpful:
http://msdn.microsoft.com/en-us/library/bb299886.aspx
For the ones who still think that RFC are more important than blogs and opinion based misconceptions, let's try to answer clarifying some points.
I'm not going to repeat all the correct differences already mentioned in previous answers, here I'm just trying adding value summarizing some crucial part rfc7159
Extracts from https://www.rfc-editor.org/rfc/rfc7159
JavaScript Object Notation (JSON) is a text format for the
serialization of structured data. It is derived from the object
literals of JavaScript, as defined in the ECMAScript Programming
Language Standard, Third Edition [ECMA-262].
JSON can represent four primitive types (strings, numbers, booleans,
and null) and two structured types (objects and arrays).
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.
begin-object = ws %x7B ws ; { left curly bracket
end-object = ws %x7D ws ; } right curly bracket
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names: false null true
An object structure is represented as a pair of curly brackets
The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable.
Examples (from page 12 of RFC)
This is a JSON object:
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
Its Image member is an object whose Thumbnail member is an object and
whose IDs member is an array of numbers.
There is really no such thing as a "JSON Object".
Really?
First you should know what JSON is:
It is language agnostic data-interchange format.
The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.
For example, in JSON all keys must be quoted, while in object literals this is not necessary:
// JSON:
{ "foo": "bar" }
// Object literal:
var o = { foo: "bar" };
The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:
var o = { if: "foo" }; // SyntaxError in ES3
While, using a string literal as a property name (quoting the property name) gives no problems:
var o = { "if": "foo" };
So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.
The data types in JSON are also restricted to the following values:
string
number
object
array
A literal as:
true
false
null
The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.
// Invalid JSON:
{ "foo": 'bar' }
The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.
// Invalid JSON:
{ "foo": 0xFF }
Here is one surprising difference: you can not use undefined in json and all object fields with undefined values will disappear after JSON.stringify
let object = { "a": undefined } ;
let badJSON= '{ "a": undefined }';
console.log('valid JS object :', object );
console.log('JSON from object:', JSON.stringify(object) );
console.log('invalid json :', JSON.parse(badJSON) );
🙈🙉🙊
Javascript Object Literal vs JSON:
Object literal syntax is a very convenient way to create javascript objects
The JSON language, which stands for 'Javascript object notation', has its syntax derived from javascript object literal syntax. It is used as a programming language independent textual data transfer format.
Example:
JS object notation, used in JS to create objects in the code conveniently:
const JS_Object = {
1: 2, // the key here is the number 1, the value is the number 2
a: 'b', // the key is the string a, the value is the string b
func: function () { console.log('hi') }
// the key is func, the value is the function
}
Example of JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
Main differences:
All object keys in JSON must be strings. In Javascript object keys can be strings or numbers
All strings in JSON must be quoted in "double quotes". Whereas in Javascript both single quotes and double quotes are allowed. Even with no quotes in the Javascript object notation the object keys are implicitly casted to strings.
In JSON a function cannot be defined as a value of an object (since this is Javascript specific). In Javascript this is completely legal.
Javascript build in JSON object:
JSON objects can be easily converted to Javascript and vice versa using the built in JSON object which Javascript offers in its runtime. For example:
const Object = {
property1: true,
property2: false,
}; // creating object with JS object literal syntax
const JSON_object = JSON.stringify(Object); // stringify JS object to a JSON string
console.log(JSON_object); // note that the (string) keys are in double quotes
const JS_object = JSON.parse(JSON_object); // parse JSON string to JS object
console.log(JS_object.property1, JS_object.property2);
// accessing keys of the newly created object

Why is swapping characters this way valid JavaScript?

I am getting confused on how this snippet of code works. I would assume that the A would need to be 'A' in order for these two characters to swap, but it works. Also, is there a name for what this is doing? From the looks of it, I think it is destructuring, but I'm not certain.
var translations = {
A : 'U'
};
console.log(translations['A']); //returns U
I would have assumed you need to write it this way:
var translations = {
'A' : 'U'
};
console.log(translations['A']); //also returns U
https://jsfiddle.net/ud37asp8/14/
Object or property keys can be either an identifier name (i.e. identifiers + reserved words), a string literal, or a numeric literal. It does not really matter whether you call it A or 'A' in the way of accessing it. https://ecma-international.org/ecma-262/6.0/#sec-object-initializer
Property names
Property names must be strings. This means that non-string objects
cannot be used as keys in the object. Any non-string object, including
a number, is typecasted into a string via the toString method.
var object = {};
object['1'] = 'value';
console.log(object[1]);
This outputs "value", since 1 is type-casted into '1'.
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
console.log(object[bar]);
This also outputs "value", since both foo and bar are converted to the
same string. In the SpiderMonkey JavaScript engine, this string would
be "['object Object']".
Also what you are doing is basically creating an Object. I do not see you destroying it anywhere.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
Creating objects
However, the advantage of the literal or initializer notation is, that
you are able to quickly create objects with properties inside the
curly braces. You simply notate a list of key: value pairs delimited
by comma. The following code creates an object with three properties
and the keys are "foo", "age" and "baz". The values of these keys are
a string "bar", a number 42, and another object.
var object = {
foo: 'bar',
age: 42,
baz: {myProp: 12}
}
Accessing properties
Once you have created an object, you might want to read or change
them. Object properties can be accessed by using the dot notation or
the bracket notation. See property accessors for detailed information.
object.foo; // "bar"
object['age']; // 42
object.foo = 'baz';
One can think of an object as an associative array (a.k.a. map,
dictionary, hash, lookup table). The keys in this array are the names
of the object's properties. It's typical when speaking of an object's
properties to make a distinction between properties and methods.
However, the property/method distinction is little more than a
convention. A method is simply a property that can be called, for
example if it has a reference to a Function instance as its value.

Javascript objects properties vs array values

I'm trying to learn javascript (coming from Delphi/pascal) and am unclear about the similarities and differences between object properties and array values. I did try searching the archives and the web for this answer.
Consider the following code:
function Show(Arr) {
var str ='';
for (var Val in Arr) {
str += Val + '::' + Arr[Val] + '\n';
}
return str;
}
var str = '';
var A1 = ["Yellow", "Red", "Blue"];
var A2 = {"color":"red", "Size": 5, "taste":"sour"}
alert(Show(A1));
//OUTPUTS:
// 0::Yellow
// 1::Red
// 2::Blue
A1.push("Green");
alert(Show(A1));
//OUTPUTS:
// 0::Yellow
// 1::Red
// 2::Blue
// 3::Green
alert('Length: '+A1.length);
//OUTPUTS:
// Length: 4
alert(Show(A2));
//OUTPUTS:
// color::red
// Size::5
// taste:sour
alert('Length: '+A2.length);
//OUTPUTS:
// Length: undefined
A2.push("Green");
//ERROR --> execution stops on jsfiddle.net.
alert("OK"); //<-- never executed
alert(Show(A2)); //<-- never executed
I know that almost everything is an object in javascript. I have been reading here (http://javascript.info/tutorial/objects) and here (http://www.w3schools.com/js/js_objects.asp).
I see that an array can be accessed by index, e.g. A1[3] --> Blue, as in other languages. But I see also that a property can be accessed this way, e.g. A2["Size"] --> 5. So at first blush, it looks like array values and property values are essentially the same. But arrays can be extended with a .push(value) command, whereas properties can't.
It is coincidence that my Show function works for both arrays and objects?
Actually, as I have written this and researched the topic, is it just that all arrays are objects, but not all objects are array? So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?
Any help clarifying this would be appreciated. Thanks.
So at first blush, it looks like array values and property values are essentially the same.
Array entries and object properties are indeed the same thing, because JavaScript's standard arrays aren't really arrays at all, they're just objects with some added features. Two of those features are the special length property, and the push function, which is why you don't see those with A2.
Your observation about bracketed notation is particularly spot-on. In JavaScript, you can access object properties using bracketed notation and a string, like this:
var o = {answer: 42};
console.log(o['answer']); // 42
It's not well-known that this is exactly what you're doing when using an array "index":
var a = ['a', 'b', 'c'];
console.log(a[1]); // b
The 1 we're using with a[1], technically according to the specification, is coerced to a string (a["1"]), and then that property name is used to look up the property on the object.
So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?
No, for-in works the same with all objects. It iterates the names of the enumerable properties of the object. Whether you're using an array or any other object doesn't matter.
Note that not all properties are enumerable. For instance, Array#length isn't, nor is Array#push or Object#toString or any of the other built-in properties of objects.
But for instance, you can see that for-in is the same for arrays as for other objects like this:
var a = ['zero']; // An array with one entry
a.answer = 42; // We've added a property to the object that isn't an array entry
console.log(a.length); // 1, because `length` only relates to array "indexes" as
// defined by the specification
var key;
for (key in a) {
console.log(key + "=" + value);
}
// Shows (in *no reliable order*):
// 0=zero
// answer=42
More about for-in:
Myths and realities of for..in (on my blog)
My answer to the question For each in array, how to do that in JavaScript? here on SO

Javascript Array Object vs Array Like Objects - Clarification

I was trying to stringify an array-like object that was declared as an array object and found that JSON.stringify wasn't processing correctly array-like object when it is defined as an array object.
See below for more clarity, --> jsFiddle
var simpleArray = []; //note that it is defined as Array Object
alert(typeof simpleArray); // returns object -> Array Object
simpleArray ['test1'] = 'test 1';
simpleArray ['test2'] = 'test 2';
alert(JSON.stringify(simpleArray)); //returns []
It worked fine and returned me {"test1":"test 1","test2":"test 2"} when I changed
var simpleArray = []; to var simpleArray = {};.
Can someone shed some light or some reference where I can read more?
Edit:
Question: When typeof simpleArray = [] and simpleArray = {} returned object, why JSON.stringify wasn't able to return {"test1":"test 1","test2":"test 2"} in both cases?
The difference is the indexes. When you use an array [] the indexes can only be positive integers.
So the following is wrong:
var array = [ ];
array['test1'] = 'test 1';
array['test2'] = 'test 2';
because test1 and test2 are not integers. In order to fix it you need to use integer based indexes:
var array = [ ];
array[0] = 'test 1';
array[1] = 'test 2';
or if you declare a javascript object then the properties can be any strings:
var array = { };
array['test1'] = 'test 1';
array['test2'] = 'test 2';
which is equivalent to:
var array = { };
array.test1 = 'test 1';
array.test2 = 'test 2';
You don't want an array. When you want an "associative array" in JavaScript, you really want an object, {}.
You can distinguish them with instanceof Array:
[] instanceof Array // true
({}) instanceof Array // false
EDIT: it can process it. It serializes all of the elements of the array. However, to be an element, there must be a numeric key. In this case, there are none.
This is nothing unique to JSON. It's consistent with toSource and the length property.
"Can someone shed some light or some reference where I can read more?"
When you're dealing with JSON data, you can refer to json.org to read about the requirements of the specification.
In JSON, an Array is an order list of values separated by ,.
So the JSON.stringify() is simply ignoring anything that couldn't be represented as a simple ordered list.
So if you do...
var simpleArray = [];
simpleArray.foo = 'bar';
...you're still giving an Array, so it is expecting only numeric indices, and ignoring anything else.
Because JSON is language independent, the methods for working with JSON need to make a decision about which language structure is the best fit for each JSON structure.
So JSON has the following structures...
{} // object
[] // array
You should note that though the look very similar to JavaScript objects and arrays, they're not strictly the same.
Any JavaScript structures used to create JSON structures must conform to what the JSON structures will allow. This is why the non-numeric properties are removed excluded.
While JavaScript doesn't mind them, JSON won't tolerate them.
When JSON.stringify encounters an array, it iterates in a similar way to a for loop from 0 to simpleArray.length to find the values. For example:
var a = [];
a[5] = "abc";
alert(JSON.stringify(a)); // alerts [null,null,null,null,null,"abc"]
Therefore setting properties on it will be completely invisible to JSON.
However defining the object with {} makes JSON treat it as an object, and therefore it loops over the object's properties (excluding inherited properties from the prototype chain). In this manner it can find your test1 and test2 properties, and successfully returns what you expect.
The differences between Array instances and other objects are specified in the ECMAScript Language Specification, Edition 5.1, section 15.4.
You will find there that while you can use the bracket property accessor syntax with all object references --
objRef[propertyName]
-- Array instances are special. Only using a parameter value which string representation is that of an unsigned 32-bit integer value less than 232-1 accesses an element of the encapsulated array structure, and write access affects the value of the Array instance's length property.
Section 15.12 specifies the JSON object and its stringify method accordingly.
In Javascript, everything is an object, so even Arrays.
This is why you get:
>> var l = [1, 2];
>> typeof l
"object"
Arrays are stored the same way as objects. So, in fact, arrays are only hashtable objects. The index you provide when accessing e.g.
>> l[0]
is not interpreted as an offset, but is hashed and then searched for.
So Arrays, are just objects (with some builtin array-methods) and so you can treat them like objects and put a value under a certain key.
But only those keys indexed by numbers are used to compute the length.
>> var l = []
>> l.length
0
>> l[5] = 1;
>> l.length
6
>> l
[undefined, undefined, undefined, undefined, undefined, 1]
>> l.hello = "Hello"
>> l.length
6
Read Array - MDN for more information
and Associative Arrays considered harmful why you should not do this.
Your code is not semantically correct, but because most JavaScript engines are really nice on the programmer they allow these types of mistakes.
A quick test case:
var a = [];
a.b = "c";
console.log(JSON.stringify(a));//yields [], and not {"b":"c"} as you might expect
This might be because of some strictness in JSON.stringify which still treats a like an Array.
I wouldn't worry about it overly much. This is a situation that should not occur in your program because it is an error. JSLint is a popular tool to catch these and many more potential problems in your code.

Associative array versus object in JavaScript

In my script there is a need to create a hash table, and I searched in google for this. Most of the folks are recommending JavaScript object for this purpose. The The problem is some of the keys in the hash table have a "." in them. I am able to create these keys easily with the associative arrays.
I don't understand why associative arrays are bad. The first thing that is mentioned on the sites that I looked at is the length property.
I am coming from the Perl background, where I used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair. If these are my common uses, can I safely use an associative array?
In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:
var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';
alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'
If you're using them already and they work, you're safe.
In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:
var obj = {"my.key": "myValue"};
vs.
var obj = [];
obj["my.key"] = "myValue";
Therefore never use the array object for this, but just the regular object.
Some functionality:
var obj = {}; // Initialized empty object
Delete a key-value pair:
delete obj[key];
Check if a key exists:
key in obj;
Get the key value:
obj[key];
Add a key-value pair:
obj[key] = value;
Because there is no such thing as built-in associative arrays in JavaScript. That's why it's bad.
In fact, when you use something like:
theArray["a"] = "Hello, World!";
It simply creates a property called "a" and set its value to "Hello, World!". This is why the length is always 0, and why the output of alert(theArray) is empty.
Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript. Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype.
So, a Perl hash and an ECMAScript object behave similarly. You might not know that you can access object properties not only via a dot, but also with brackets and strings, like
var myObj = { foo: 42 };
myObj.foo; // 42
myObj['foo']; // 42
Knowing that, you can also use keys with .
var myObj = { };
myObj['hello.foo.world'] = 42;
Of course, you can access that key only with the bracket notation.
You can use . in key names on JavaScript objects (AKA associative arrays) if you'd like; they're accepted without issue. The minor drawback is you can't use shortcut notations with the dotted keys, e.g.
var x = {};
x['hello'] = 'there';
alert(x.hello);
is perfectly acceptable and will pop up an alert with 'there' in it. But if you use a dotted name:
var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);
will fail, as JavaScript will look for an attribute named this in the x object, which does not exist. There is only the this.is attribute.
There isn't an associative array. It's just an object.
foo.bar; // Equivalent to...
foo["bar"]; // Looks like associative array.
For the sake of convenience of using data, there should be no difference between an object and an array. You can think of it as an object or you can think of it as an associative array. At the end, you can just think of everything as data.
For PHP, [ ] accepts 0, 1, or more items(array), and it is called an associative array. It is JSON in PHP's coat:
$data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];
For JavaScript, { } accepts 0, 1, or more items(array), and it is called an object. This data format is JSON:
data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};
I just call them data. The simplest way to describe data is JSON, or its variants.

Categories

Resources