2015-04-23 38 views
2

嘿傢伙我對Java腳本很陌生,但已經閱讀了一些關於js的初學者書籍,我正在通過MDN文檔瞭解arguments如何在js中工作並碰到以下腳本:瞭解javascript中參數的基礎

function list(type) { 
     var result = "<" + type + "l><li>"; 
     var args = Array.prototype.slice.call(arguments, 1); 
     result += args.join("</li><li>"); 
     result += "</li></" + type + "l>"; // end list 

     return result; 
    } 

    var listHTML = list("u", "One", "Two", "Three"); 

console.log(listHTML); // "<ul><li>One</li><li>Two</li><li>Three</li></ul>" 

仔細看看打印出來的東西。

現在這與我預期它的工作方式非常直觀。

所以讓我們打破它,假設我調用函數列表如下圖所示:

list("u", "One", "Two", "Three"); 
現在

什麼列表功能的情況是

var result = "<" + type + "l><li>"; // here type is still -- "u", "One", "Two", "Three" , than why does only u get inserted ?? 
    var args = Array.prototype.slice.call(arguments, 1); // in understand this line 
    result += args.join("</li><li>"); 
    result += "</li></" + type + "l>"; // end list 

    return result; 

對這一計劃的工作,我想通了,關鍵是第一行只有「u」被插入,而不是所有的參數(請參閱我的評論),但是這段代碼是如何完成的,我知道它是一段簡單的代碼片段,但我真的很開心在這裏,抓着我的頭看着這段代碼。

有人可以解釋一下嗎?

編輯我的預期成果是:

<uOneTwoThreel><li>One</li><li>Two</li><li>Three</li></uOneTwoThreel> 

感謝。

亞歷-Z

+1

你有什麼期望的輸出? –

+0

'type'不是「你」,「一個」,「兩個」,「三個」 - 它只是「你」。如果你有'function fn(arg1,arg2){// body}',並且你把它叫做fn(「foo」,「bar」,「baz」)','arg1'將會是''foo'', 'arg2'將會是'「baz」',並且第三個參數將不會爲它創建一個變量,但是將會在'arguments' – Sacho

+0

@ArunPJohny編輯! –

回答

5

JavaScript中的僞陣列arguments包含一切已傳遞給函數,而在函數的參數列表中列出的命名參數得到填補與傳​​遞的值忽略額外的參數和如果沒有足夠的參數傳遞,則設置undefined

例如主叫function f(x, y){...}f(1,2,3,4)與將具有

  • x = 1
  • y = 2
  • arguments = [1, 2, 3, 4]

和,而不是調用function g(x, y){...}g(1)將具有

  • x = 1
  • y = undefined
  • arguments = [1]

注意arguments不是數組,因此不能使用所有陣列方法(如join)。這就是使用slice技巧轉換跳過數組中第一個參數的所有參數的原因。

2

這裏的問題是type是一個參數,它將保存方法調用的第一個參數的值,在您的情況下爲u。由於您沒有像傳遞的參數那樣多的參數,其餘的參數將沒有正式的參考。

function list() { 
    //this will create an array params which will have all the values of the arguments object 
    var params = Array.prototype.slice.call(arguments, 0); 

    //we joins all the passes params to create the type 
    var type = params.join(''); 
    var result = "<" + type + "l><li>"; 

    //we ignores the first parameter here 
    var args = params.slice(1); 
    result += args.join("</li><li>"); 
    result += "</li></" + type + "l>"; 

    return result; 
} 

var listHTML = list("u", "One", "Two", "Three"); 

console.log(listHTML); 

演示:Fiddle