Ext.each(Extjs中的迭代方法)

EXTJS 有很多的迭代方法,例如,你也许已知道的Ext.each,但还有另外一些不为人知且很有用的方法。首先,简要回顾下Ext.each:

Ext.each

为每一个数组的成员应用同一个方法,它基本上是一个更方便的循环形式

var people = ['Bill', 'Saul', 'Gaius'];

//using each to detect Cylons:
Ext.each(people, function (person, index)
{
    var cylon = (index + 1) % 2 == 0; //every second man is a toaster
    alert(person + (cylon ? ' is ' : ' is not ') + 'a fraking cylon');
});

//is the same as
for (var i = 0; i < people.length; i++)
{
    var person = people[i];
    var cylon = (index + 1) % 2 == 0; //every second man is a toaster

    alert(person + (cylon ? ' is ' : ' is not ') + 'a frakin cylon');
};

Ext.iterate

Ext.iterate 与 Ext.each 类似针对非数组对象. 通常用在for-in 循环中:

var ships = { 'Bill': 'Galactica', 'Laura': 'Colonial One' };

Ext.iterate(ships, function (key, value)
{
    alert(key + "'s ship is the " + value);
});

//is the same as
for (key in ships)
{
    var value = ships[key];
    alert(key + "'s ship is the " + value);
}

用Ext.iterate在数组上,与Ext.each完全相同。  each和iterate方法都有第三个可选参数scope。  另一个有用的技巧是你可以更方便的重用相同的方法:

var myFunction = function (item, index)
{
    //does some clever thing
}

Ext.each(people, myFunction);
Ext.each(['another', 'array'], myFunction);

Ext.pluck

(4.0.0之后过时) Ext.pluck从对象数组捕获特定的属性

var animals = [
  { name: 'Ed', species: 'Unknown' },
  { name: 'Bumble', species: 'Cat' },
  { name: 'Triumph', species: 'Insult Dog' }
];

Ext.pluck(animals, 'species'); //returns ['Unknown', 'Cat', 'Insult Dog']
Ext.pluck(animals, 'name'); //returns ['Ed', 'Bumble', 'Triumph']

此方法自4.0.0不建议使用,请用Ext.Array.pluck代替.

Ext.invoke

(4.0.0之后过时)数组中所有成员调用同一个方法,并返回结果,使用用上例animals:

var describeAnimal = function (animal)
{
    return String.format("{0} is a {1}", animal.name, animal.species);
}

var describedAnimals = Ext.invoke(animals, describeAnimal);
console.log(describedAnimals); // ['Ed is a Unknown', 'Bumble is a Cat', 'Triumph is a Insult Dog'];

Ext.invoke与Ruby的集合方法类似,使得更容易转换数组,任何增加的参数都可通过Ext.invoke传递。  此方法自4.0.0不建议使用,4.X系列版本后将被移除。

Ext.Partition

Ext.Partition将数组拆分成两部分。

var trees = [
  { name: 'Oak', height: 20 },
  { name: 'Willow', height: 10 },
  { name: 'Cactus', height: 5 }
];

var isTall = function (tree) { return tree.height > 15 };

Ext.partition(trees, isTall);

//returns:
[
  [{ name: 'Oak', height: 20}],
  [{ name: 'Willow', height: 10 }, { name: 'Cactus', height: 5}]
]

此方法自4.0.0不建议使用,4.X系列版本后将被移除。

数学方法

var numbers = [1, 2, 3, 4, 5];
Ext.min(numbers); //1
Ext.max(numbers); //5
Ext.sum(numbers); //15
Ext.mean(numbers); //3
posted @ 2021-09-27 20:36  痴迷的小和尚  阅读(292)  评论(0编辑  收藏  举报