我正在阅读《JavaScript 忍者的 secret 》一书,我被代码示例中的一些语法所困。如果您有这本书,可以在第 17 页找到代码,下面是示例。
function runTest() {
if (!paused && queue.length) {
queue.shift()();
if(!paused) {
resume();
}
}
}
有人可以解释第 3 行发生了什么吗? queue.shift()();
有什么作用?我查看了 MDN 上的文档,并在 JSFiddle 中玩了一点,但我似乎无法弄清楚。我怀疑它可能会从数组中删除前两个元素,但这没有用,如果没有第二组 ()
,代码示例将无法运行。
如果需要更多代码来理解这一点,请告诉我,我可以添加更多。
最佳答案
shift
移除数组中的第一个对象,并将数组中的所有对象shifts。
然后返回被移除的对象。
在您的示例中,对象必须是一个函数,然后调用该函数。
这是以下内容的简写:
var removedFunc = queue.shift();
removedFunc();
有关 shift
的更多信息,请参阅 MDN 文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
The shift() method removes the first element from an array and returns that element. This method changes the length of the array.
示例( Demo ):
var a = [];
a.push(function(){
alert("a");
});
a.push(function(){
alert("b");
});
a.shift()(); //alerts a
a.shift()(); //alerts b
关于javascript - 对 array.shift() 感到困惑 - 来自 Secrets of the JS Ninja 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136888/