2015-04-23 86 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