English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Arreglo JSON

El array JSON es similar al array de JavaScript.

El array JSON representa una lista ordenada de valores. Puede almacenar cadenas de caracteres, números, valores booleanos o objetos en un array JSON.

Array en objeto JSON

El array puede ser el valor de una propiedad de objeto.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": [ "Deadpool", "Hulk", "Thanos" ]
}
Prueba y observa ‹/›

Acceder al valor del array

Se puede usar el índice de cada elemento del array para acceder al valor del array.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": [ "Deadpool", "Hulk", "Thanos" ]
}
myJSON.friends[2  // returns "Thanos"
Prueba y observa ‹/›

Recorrer el array

Elfor-inEl bucle se puede usar para recorrer un array.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": [ "Deadpool", "Hulk", "Thanos" ]
}
for (let x in myJSON.friends) {
document.getElementById("output").innerHTML += myJSON.friends[x];
}
Prueba y observa ‹/›

JSON对象中的嵌套数组

在嵌套数组中,另一个数组也可以是一个数组的值。

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": [
  { "heroName": "Deadpool", "skills": ["Martial artist", "Assassin"] },
  { "heroName": "Hulk", "skills": ["Superhuman Speed", "Superhuman Strength"] }, 
  { "heroName": "Thanos", "skills": ["Telepathy", "Superhuman senses"] }
  ] 
}
myJSON.friends[2].heroName;  // returns "Thanos"
Prueba y observa ‹/›

嵌套for-in循环可用于访问数组内部的数组。

for(let i in myJSON.friends) {
   x += "

" + myJSON.friends[i].heroName + "

";    for(let j in myJSON.friends[i].skills) {       x += myJSON.friends[i].skills[j] + "
";    } } document.getElementById("output").innerHTML = x;
Prueba y observa ‹/›

修改数组值

索引号可用于值的修改。

myJSON.friends[2] = "Ant-man";
Prueba y observa ‹/›

删除数组项

可以使用delete关键字删除数组的值。

delete myJSON.friends[2
Prueba y observa ‹/›