我正在研究AngularJs教程,我想访问JSON。我不明白为什么在教程中他们使用[]来访问JSON。当用户点击“a tag”时,它会将airport.code放入setAirport函数并返回currentAirport.name 这是代码:
HTML:
<html ng-app>
<head>
<title>Demo</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<h1>AngulAir</h1>
<ul>
<li ng-repeat="airport in airports">
<a href="" ng-click="setAirport(airport.code)">
{{airport.code}} - {{airport.city}}
</a>
</li>
</ul>
<p ng-show="currentAirport">Current Airport : {{currentAirport.name}}</p>
</div>
这是JS代码:
function AppCtrl ($scope) {
$scope.airports = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland",
"destinations": [
"LAX",
"SFO"
]
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis",
"destinations": [
"LAX",
"MKE"
]
}
};
$scope.currentAirport = null;
$scope.setAirport = function (code){
$scope.currentAirport = $scope.airports[code];
};
}
你可以在上一个陈述中看到---&gt; $ scope.currentAirport = $ scope.airports [code];它使用[]来访问JSON。我不明白为什么用这种方式。我尝试在另一种情况下进行实验,它似乎工作方式不同,这是我的实验:
HTML:
<html>
<head>
<title>hello world</title>
</head>
<body>
</body>
<script type="text/javascript" src=jsfile.js></script>
<script type="text/javascript">
alert(airports[code]);
</script>
JS档案:
airports = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland",
"destinations": [
"LAX",
"SFO"
]
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis",
"destinations": [
"LAX",
"MKE"
]
}
};
我在浏览器上看到这个“ReferenceError:找不到变量:代码”为什么?本声明的JSON访问方式-----&gt; $ scope.currentAirport = $ scope.airports [code];不等于这个陈述-----&gt;警报(机场[代码]); ?????
为什么在第二种情况下我不能使用[]?有谁知道请告诉我
答案 0 :(得分:3)
在第一个例子中:
$scope.setAirport = function (code){
$scope.currentAirport = $scope.airports[code];
};
code
传递给该函数,他们使用它引用机场对象中的机场代码。
在你的例子中:
alert(airports[code]);
code
未定义。
您需要定义代码,或手动将机场代码传递给它。