Extjs中的迭代方法

分類: extjs 49人閱讀 評論(0) 收藏 舉報

EXTJS 有很多的迭代方法,例如,你也許已知道的Ext.each,但還有另外一些不為人知且很有用的方法。首先,簡要回顧下Ext.each:

Ext.each

為每一個數(shù)組的成員應(yīng)用同一個方法,它基本上是一個更方便的循環(huán)形式

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 類似針對非數(shù)組對象. 通常用在for-in 循環(huán)中:
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在數(shù)組上,與Ext.each完全相同。 
each和iterate方法都有第三個可選參數(shù)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從對象數(shù)組捕獲特定的屬性
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之后過時)數(shù)組中所有成員調(diào)用同一個方法,并返回結(jié)果,使用用上例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的集合方法類似,使得更容易轉(zhuǎn)換數(shù)組,任何增加的參數(shù)都可通過Ext.invoke傳遞。 
此方法自4.0.0不建議使用,4.X系列版本后將被移除。

Ext.Partition

Ext.Partition將數(shù)組拆分成兩部分。

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系列版本后將被移除。

數(shù)學(xué)方法

var numbers = [1, 2, 3, 4, 5];
Ext.min(numbers); //1
Ext.max(numbers); //5
Ext.sum(numbers); //15
Ext.mean(numbers); //3