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

原文地址:Ext JS iterator functions

http://www.veryhuo.com/a/view/36701.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章