Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSON Arrays

Here is a string in JSON format:

‘[“Ford”, “BMW”, “Fiat”]’

The JSON string contains a JSON array literal:

[“Ford”“BMW”“Fiat”]

Arrays in JSON are similar to arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean, or null.

In JavaScript, array values can be all of the above, as well as any other valid JavaScript expression, including functions, dates, and undefined.

JavaScript Arrays

You can create a JavaScript array from an array literal.

Example

myArray = [“Ford”“BMW”“Fiat”];

You can create a JavaScript array by parsing a JSON string.

Example

myJSON = ‘[“Ford”, “BMW”, “Fiat”]’;
myArray = JSON.parse(myJSON);

Accessing Array Values

You can access array values using their index.

Example

myArray[0];

Arrays in Objects

Objects can include arrays as their values.

Example

{
“name”:“John”,
“age”:30,
“cars”:[“Ford”“BMW”“Fiat”]
}

Array values are accessed using their index.

Example

myObj.cars[0];

Looping Through an Array

Array values are accessed using their index.

Example

for (let i in myObj.cars) {
  += myObj.cars[i];
}

Alternatively, you can use a for loop.

Example

for (let i 0; i < myObj.cars.length; i++) {
  x += myObj.cars[i];
}