在 JS Array 中支持两个方法,shift() 和 pop(),分别是指从一个数据中的最前面和最后面删除一个值,并返删除值。看一个示例就明白了:
复制代码 代码如下:
var arr = ['s','o','f','i','s','h'];
arr.shift(); // 返回 's'
arr; // 目前是 ['o','f','i','s','h']
arr.pop() // 返回 'h'
arr // 目前是 ['o','f','i','s']
这里,我们可以利用函数的 arguments 对象,以及 Array 中的 shift 和 pop 来实现灵活的应用。
一、使用 shift
如何实现一个 .bind() 方法,让 fn api 如下:
复制代码 代码如下:
// fn 的作用域限定于 object 下
// 除 object 外,所有 bind 方法的参数都将传给 fn
fn.bind(object, param1, param2, [, paramN]);
复制代码 代码如下:
// 来自 Prototype.js 的 [`.bind`]() 方法
Function.prototype.bind = function(){
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
二、使用 pop
最近在试用 seajs,我们就拿它的一个 api 来说吧:
复制代码 代码如下:
define(id, dependencies, callback)
复制代码 代码如下:
var define = function(){
// 取出这个 callback
var args = [].slice.call(arguments)
fn = args.pop();
// 做点其他神马事
fn.apply(null, args)
// ...
},
callback = function(){
var args = arguments, i = 0, len = args.length;
if(len === 0) console.log('只有一个 callback');
for(;i<len;i++) {
console.log(args[i]);
}
}
// 看看他们三个的执行结果
define(callback);
define('有两个参数', callback);
define('有三个参数', 'hello world', callback);
新闻热点
疑难解答
图片精选