基本的Javascript和JSON对象

时间:2017-05-09 04:35:09

标签: javascript

function load() {
// JavaScript
var myObject = new Object();
myObject.name = "Cessna";
myObject.model = "152";
myObject.year = "1984";
myObject.color1 = "white";
myObject.color2 = "blue";

// JSON
var myObject_JSON = {"name":"Cessna", "model":"152", "year":"1984", "color1":"white", "color2":"blue"};

var strJava = "JavaScript Object\n";
    strJava += "Name    = " + myOjbect.name   + "\n";
    strJava += "Model   = " + myOjbect.model  + "\n";
    strJava += "Year    = " + myOjbect.year   + "\n";
    strJava += "Color 1 = " + myOjbect.color1 + "\n";
    strJava += "Color 2 = " + myOjbect.color2;

var strJSON = "JSON Object\n";
    strJSON += "Name    = " + myObject_JSON["name"]   + "\n";
    strJSON += "Model   = " + myObject_JSON["model"]  + "\n";
    strJSON += "Year    = " + myObject_JSON["year"]   + "\n";
    strJSON += "Color 1 = " + myObject_JSON["color1"] + "\n";
    strJSON += "Color 2 = " + myObject_JSON["color2"];

window.alert(strJava);
window.alert(strJSON);  
}

所以我的任务是将JavaScript对象转换为JSON对象。 我想检查一下转换是否正确。因此,我试图显示每个的价值。 但是我无法使window.alert()函数正常工作。页面加载时不会显示任何内容。

P / S:<body onload="load();">

时有一个HTML文件

为什么警报功能无法成功运行的任何建议?

2 个答案:

答案 0 :(得分:0)

您定义了myObject变量但使用了myOjbect

在下面的代码段中,我只是将myOjbect更正为myObject

window.onload = load();
function load() {
  // JavaScript
  var myObject = new Object();
  myObject.name = "Cessna";
  myObject.model = "152";
  myObject.year = "1984";
  myObject.color1 = "white";
  myObject.color2 = "blue";

  // JSON
  var myObject_JSON = {
    "name": "Cessna",
    "model": "152",
    "year": "1984",
    "color1": "white",
    "color2": "blue"
  };

  var strJava = "JavaScript Object\n";
  strJava += "Name    = " + myObject.name + "\n";
  strJava += "Model   = " + myObject.model + "\n";
  strJava += "Year    = " + myObject.year + "\n";
  strJava += "Color 1 = " + myObject.color1 + "\n";
  strJava += "Color 2 = " + myObject.color2;

  var strJSON = "JSON Object\n";
  strJSON += "Name    = " + myObject_JSON["name"] + "\n";
  strJSON += "Model   = " + myObject_JSON["model"] + "\n";
  strJSON += "Year    = " + myObject_JSON["year"] + "\n";
  strJSON += "Color 1 = " + myObject_JSON["color1"] + "\n";
  strJSON += "Color 2 = " + myObject_JSON["color2"];

  window.alert(strJava);
  window.alert(strJSON);
}
<div>
</div>

答案 1 :(得分:0)

这是因为您定义了myObject变量但使用了myOjbect。