有没有办法在对象上获取带有角度的迭代号

Is there a way to get the iteration number with angular foreach on an object

本文关键字:代号 迭代 获取 对象 有没有      更新时间:2023-09-26

有什么方法可以在角度foreach内获取迭代号(当遍历像:{'foo': 'blah', 'blah': 'foo'}这样的对象时?因此,在这种情况下,使用我的迭代器函数,值将是"blah",然后是"foo",而键将是"foo",然后是"blah"

迭代对象时forEach的角度不会告诉您对象键的迭代次数。

迭代数组时,它不会告诉您它运行了多少次,而是告诉您它在数组中的当前位置。可能只是我迂腐,但有区别。

但是,可以在对象键中给出其当前位置的替代方法是使用本机Object.keys()。它将返回一个对象键的数组,然后您可以像普通数组一样迭代它们并获取您在该数组中的当前位置。

var obj = {'foo': 'blah', 'blah': 'foo'};
Object.keys(obj)
    .forEach(function (key, index) {
        console.log('Key', key, 'Value', obj[key]);
        console.log('Ive ran ', index);
    });

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

是的,像这样:

angular.forEach(array, function (item, index) {
    //index
});
是的,

它是直接从角度文档传入foreach函数调用的第二个参数

https://docs.angularjs.org/api/ng/function/angular.forEach

angular.forEach(obj, iterator, [context]);
angular.forEach(var,function(value,key){
  console.log(key);
})