2

假设我有一个如下所示的 JSON 文档/JavaScript 对象:

var animal = {
  "squirrel": "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae."
}

在 JavaScript 中,这会发生:

console.log(animal.squirrel) //Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae

假设我想将rank对象添加到:

var animal = {
  "squirrel": {   
    "rank": {
      "Kingdom": "Animalia",
      "Phylum": "Chordata",
      "Class": "Mammalia",
      "Order": "Rodentia",
      "Suborder": "Sciuromorpha",
      "Family": "Sciuridae"
    }
  }
}

排名可以像这样访问:

animal.squirrel.rank

但我仍然希望对象的顶层animal.squirrel是包含上述句子的字符串。

这可能吗?

4

2 回答 2

5

在 JSON 中是不可能的。然而,在 JavaScript 中,您可以做一些事情。您可以提供toString将对象转换为字符串时使用的方法:

var animal = {
  "squirrel": {   
    "rank": {
      "Kingdom": "Animalia",
      "Phylum": "Chordata",
      "Class": "Mammalia",
      "Order": "Rodentia",
      "Suborder": "Sciuromorpha",
      "Family": "Sciuridae"
    },
    toString: function() {
      return "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.";
    }
  }
};

您还可以使用String对象:

var animal = {
    squirrel: new String("Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.")
};

animal.squirrel.rank = {
    "Kingdom": "Animalia",
    "Phylum": "Chordata",
    "Class": "Mammalia",
    "Order": "Rodentia",
    "Suborder": "Sciuromorpha",
    "Family": "Sciuridae"
};

后者的行为更像是一个字符串,但它使用一个String对象,这有时会令人沮丧并且通常是不好的做法。

于 2012-08-18T21:34:35.897 回答
1

正如其他人所说,这在任何对象上下文中都是不可能的,因此您需要将所有内容作为对象上/对象中的可访问部分来处理。

var animal = {
  "squirrel": {
    "info": "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.",
    "rank": {
      ...
    }
  }
}

而且,我认为不相关,您可以为通用设置快速访问器。

function getAnimalInfo(animalName) {
  if (!animal[animalName]) return "No info for: " + animalName;

  return animal[animalName].info;
}

所以,

console.log(getAnimalInfo("squirrel")); //Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae
于 2012-08-19T02:27:29.427 回答