简体   繁体   English

angularjs:使用键值对迭代数组

[英]angularjs : iterate array with key value pairs

I am creating an array like the following: 我正在创建一个如下所示的数组:

var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';

If is use this array in ng-repeat tag, it is not displaying anything. 如果在ng-repeat标记中使用此数组,则它不显示任何内容。 Is there any way to make it work? 有没有办法使它工作?

<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>

Is there any way to make it work? 有没有办法使它工作?

The way to go, is to creat plain object (instead of array) 要走的路,就是创建普通对象(而不是数组)

// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};

Thee is updated plunker 你是更新的plunker

Check more details what is behind for example here: 查看更多详细信息,例如:

Javascript: Understanding Objects vs Arrays and When to Use Them. Javascript:了解对象与阵列以及何时使用它们。 [Part 1] [第1部分]

Your associative array is nothing but an object, as far as JavaScript is concerned. 就JavaScript而言,关联数组只不过是一个对象。 IMO Associative arrays and Objects are almost same. IMO关联数组和对象几乎相同。

Ex: Your arr['key1'] = 'value1'; 例如:你的arr['key1'] = 'value1'; can be called as console.log(arr.key1); 可以称为console.log(arr.key1);

To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces) 要使代码工作,您需要通过删除[]并替换为{} (Curly大括号)来更改数组声明

Like this var arr = {}; 像这样var arr = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM