vapour's blog

10Mar/110

数组的小技巧

JavaScript array “extras” in detail 介绍了ES5对数组原型对象扩充的方法:forEach、map、filter、some、every、indexOf、lastIndexOf、reduce、reduceRight。这些方法不仅可以应用到数组,还可应用到拥有length属性,并且可以数字索引的对象上,例如String,arguments,DOM nodes collection等。

// get the reference to the map method
var map = Array.prototype.map;

// and call it for a string
var hello = map.call("hello world", function (char) {
  return char + "*";
});

alert(hello.join("")); // "h*e*l*l*o* *w*o*r*l*d*"

 

除了上面这些ES5的方法,join方法也可应用到拥有length属性,并且可以数字索引的对象上,示例:

var s = 'abcd'
    f = Array.prototype.join;
var str = f.call(s, '-');
alert(str);// a-b-c-d

 

文中还有一个数组方法重用字符串方法的例子:

// reuse "toUpperCase" method
var toUpperCase = String.prototype.toUpperCase;
var upper = toUpperCase.apply(["foo", "bar"]).split(",");
alert(upper); // ["FOO", "BAR"]

 

下面是John Resig 给出的获取数组最大与最小值的方法,很有创意:

function smallest(array){
    return Math.min.apply( Math, array );
}
function largest(array){
    return Math.max.apply( Math, array );
}
Tagged as: No Comments