Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a key value pair inside the square brackets [] mean?

Tags:

Let's consider the following is my object:

var n = {"aa":"x","dd":'d'};

I am using square brackets in Object.assign. It gives the following result. [aa: "x", dd: "d"]. The final code is:

var n = {"aa":"x","dd":'d'};
var m = Object.assign([],n);

// result is 
[aa: "x", dd: "d"]

in the console.log __proto__ tells this is Array, if it is array following code giving the, unexpected token error

var v = ["sss":"ddd","ccc":"ddd"]; 

What does mean?

enter image description here

like image 415
mkHun Avatar asked May 17 '19 17:05

mkHun


People also ask

What does square brackets mean in coding?

Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.

What do square brackets in Java mean?

Square brackets [] Square brackets are used for declaration of arrays and for selection of array elements. Curly brackets {} Curly brackets are used for collecting statements in blocks. For example, the definition of a class and of a method is placed between curly brackets.

What is square brackets in Python?

The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.

What is key value pair in JavaScript?

A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything. We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file.


2 Answers

Arrays are objects in JS

Arrays in JS are exotic objects, so you can assign properties to them just like any other object.

MDN says:

Arrays are list-like objects

...

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

Object.assign doesn't know the difference between an array and an object, and simply assigns keys from parameters 2+ to the object at parameter 1. This behavior shouldn't be too surprising.

const a = [];
a.foo = 42;
const b = Object.assign([], a);                  // sure, why not?
console.log(typeof a, typeof b, b.foo);          // => object object 42
console.log(Array.isArray(a), Array.isArray(b)); // => true true

The var a = ["foo": "bar"] syntax doesn't work because JS array initializers follow similar syntax to function calls. The array initializer is not syntactic sugar on the Array constructor, but it is similar in that it accepts a comma-delimited list of expressions. There's no reason to think it should behave in the same way as the object literal var obj = {"foo": "bar"} syntax, which has its own specification. That's a good thing, because it's poor practice to abuse arrays as key-value objects as much as it is to abuse functions as key-value objects:

const func = () => "hello";
func.foo = 42;
console.log(func.foo, typeof func, func()); // => 42 function hello

From the MDN article on array literals:

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

Expressions are "any valid unit of code that resolves to a value". The key: value syntax is not an expression itself, only part of the object initializer syntax, and it's absent in the MDN expression reference page.


Browser console printing is implementation-defined

Moving away from JS and into the browser, the image you've posted shows how Chrome logs arrays with properties, but this is implementation-defined according to the following specification found in console.log -> console.logger -> console.printer:

The printer operation is implementation-defined. It accepts a log level indicating severity, a List of arguments to print, and an optional object of implementation-specific formatting options. Elements appearing in args will be one of the following:

  • JavaScript objects of any type.

  • Implementation-specific representations of printable things such as a stack trace or group.

  • Objects with either generic JavaScript object formatting or optimally useful formatting applied.

...

How the implementation prints args is up to the implementation, but implementations should separate the objects by a space or something similar, as that has become a developer expectation.

Furthermore, 2.3.3. Common object formats states:

Typically objects will be printed in a format that is suitable for their context. This section describes common ways in which objects are formatted to be most useful in their context. It should be noted that the formatting described in this section is applied to implementation-specific object representations that will eventually be passed into Printer, where the actual side effect of formatting will be seen.

An object with generic JavaScript object formatting is a potentially expandable representation of a generic JavaScript object. An object with optimally useful formatting is an implementation-specific, potentially-interactive representation of an object judged to be maximally useful and informative.

Empirical evidence supports the above statements:

Firefox 67.0

ff

Edge 42.17134.1.0

edge

Neither browser shows the array's properties between the brackets, only its numerically-indexed elements (if any exist). The fact that Chrome renders these properties in its implementation of the console spec does not obligate or imply that JS should allow this syntax in its array initializer. There's simply no relationship between the browser's console presentation and the language's syntax.

like image 107
ggorlen Avatar answered Sep 20 '22 12:09

ggorlen


What you have here is an array that is abused as an object literal. An array has, for example, also a length property. Just like this, you can assign keys to an array, though you shouldn't do it.

It's not entirely clear what you want to to here, usually one uses Object.assign() with object literals rather than with arrays. They have their own functions.

Object.assign({}, n);

would be a sane use case.

like image 24
baao Avatar answered Sep 18 '22 12:09

baao