關於[].slice.call(arguments, 1) 的思考

var a = function(f){
    console.log(arguments);
}

a('show', [12,3,4,55]);

結果:['show', Array[4]]

 

  • 測試2
var a = function(f){
    console.log([].slice.call(arguments, 1));
}

a('show', [12,3,4,55]);

結果:[Array[4]]

 

  • 測試3
var a = function(f){
    console.log(arguments.slice(1));
}

a('show', [12,3,4,55]);

結果:報錯!!! **arguments.slice is not a function(...)**

 

此時就心中產生了疑惑了,爲啥在測試一中打印出來的arguments 是個數組的東西啊,爲啥會提示沒有slice這個方法呢?帶着疑問我去請教下了隊伍裏的大牛,獲得了下面的答案:數組

(function() {
    console.log(arguments instanceof Array)
})();

結果:false

arguments 並不是數組,只是訪問單個參數的方式與訪問數組元素的方式相同。所以在使用slice方法的時候,須要用相似[].slice.call(arguments, 1) 的這種方式去調用,至此,關於這條語句引起的思考也就此結束了。測試

相關文章
相關標籤/搜索