在 Javascript 中访问数组
Posted
技术标签:
【中文标题】在 Javascript 中访问数组【英文标题】:Accessing Arrays in Javascript 【发布时间】:2018-12-23 14:49:00 【问题描述】:我无法访问PayLoad
。而且我不确定我访问它的方式是否正确。我想访问PayLoad
,我所做的是:
console.log("$scope.showbroadcast::", $scope.showbroadcast][0].PayLoad);
我应该如何访问那种数据(如图所示)。
【问题讨论】:
console.log("$scope.showbroadcast::", $scope.showbroadcast][0].PayLoad['data']['txtno']); 你必须使用每个元素的索引,如下所示 【参考方案1】:payload数据是JSON字符串格式,所以先转换成JSON对象
$scope.broadcast =angular.fromJson($scope.showbroadcast][0].PayLoad) 然后您可以从中访问值: $scope.txnno = $scope.broadcast.data.txnno
【讨论】:
【参考方案2】:angular.module('MyApp', [])
.config(function() )
.controller('MyAppCtrl', ['$scope', function($scope)
$scope.name = "John";
//this array is comes from your api endpoint or any project file
$scope.array =
"myarray": [
"FinalName": "john lloyd",
"Message": "hi",
"Name": "john lloyd",
"PayLoad":
"data":
"txnno": "790....",
"subject": "BROADCAST"
,
"FinalName": "john miller",
"Message": "hi",
"Name": "john miller",
"PayLoad":
"data":
"txnno": "990....",
"subject": "TELECAST"
]
;
//If your array contains "N" elements then you have to use foreach or for loop on "myayyay" variable
$scope.array.myarray.forEach(function(i)
console.log('txnno[i]:' + i.PayLoad.data.txnno);
console.log('subject[i]:' + i.PayLoad.data.subject);
)
//If your array contains only one element and you want PayLoad object then
$scope.payload = $scope.array.myarray[0].PayLoad;
console.log($scope.payload)
//If you want to read data inside PayLoad object then
$scope.txnno = $scope.array.myarray[0].PayLoad.data.txnno;
$scope.subject = $scope.array.myarray[0].PayLoad.data.subject;
console.log($scope.txnno)
console.log($scope.subject)
]);
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-controller = "MyAppCtrl">
<h1>Hello name!</h1>
<p>txnno: txnno</p>
<p>subject: subject</p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="script.js"></script>
<script type="text/javascript">
angular.element(document).ready(function () angular.bootstrap(document, ['MyApp']); );
</script>
</body>
</html>
我还创建了一个plunker,以便您更好地了解如何从数组中获取“PayLoad”对象以及有效负载对象中的“数据”
我试图让 plunker 尽可能简单,以便初学者在他们的知识领域内获得清晰的解决方案。
【讨论】:
以上是关于在 Javascript 中访问数组的主要内容,如果未能解决你的问题,请参考以下文章