Javascript代码:它是如何工作的?

时间:2013-05-03 20:56:44

标签: javascript google-chrome-devtools

我最近完成了DevTools~> http://discover-devtools.codeschool.com/当然,在检查使用的代码时,我遇到了一些我不理解的部分:

String.prototype.repeat = function (num) {
  return new Array(num + 1).join(this);
};
因此在displayDate()方法中使用

var body = $('body')[0].outerHTML.repeat(10000);

使用此代码的重要性是什么?

其次,在displayToday()方法中,使用参数调用displayDate()方法,尽管它没有被定义为采用arg。为什么会这样?

我正在学习JS而且无法绕过这些。欢迎任何帮助。

3 个答案:

答案 0 :(得分:4)

String.prototype.repeat = function (num) {
  return new Array(num + 1).join(this);
};

此代码创建一个num+1长度的数组,填充undefined。然后使用join将其折叠为字符串,将每个未定义的值与this字符串outerHTML分隔开来。当一个数组连接成一个字符串时,undefined值就没有了,因此生成的字符串只包含显示num次的分隔符,从而“重复”该字符串。

//let . be "undefined, which when turned into a string, is just nothing
[u,u,u,...,u].join('test');
'(u)test(u)test(u)...(u)test'
'testtest...test'

至于第二个问题,JS 中的函数将始终接受参数,即使该函数不打算接受参数。在JS中定义函数中的参数只是为传递的参数赋一个名称。参数将始终转到函数,并收集在函数中可用的特殊数组中作为arguments变量。

function fn(){
  console.log(arguments); //['hello','world'];
}

foo('hello','world');

答案 1 :(得分:1)

即使您没有在声明中列出参数,也可以将参数传递给函数。您可以访问使用arguments

传递的参数
function foo () {
  console.log(arguments);
}

foo('bar'); // ['bar']
foo('bar','blerg'); // ['bar','blerg']

答案 2 :(得分:1)

这很简单。

当您更改某些内容的prototype时,在这种情况下是默认的String类,您可以将该方法用于该类的任何实例,在本例中为任何字符串。

现在让我们看一下该方法的作用。

return new Array(num + 1).join(this);

由于String.prototype.displayDate = function(num) {,该函数中this的值是字符串的值。 this引用指向当前对象,我想这是有道理的。

然后它创建一个num + 1个元素的数组,这些元素将全部用undefined初始化。 Array.prototype.join返回由您提供的事物分隔的数组元素的字符串表示形式。

在这种情况下,您有一个num +1 undefined值的数组。 undefined的字符串表示形式为"",或为空字符串。所以你最终得到空字符串+ this的值的num + 1个连接,或者你的字符串的num次。

说你的字符串是“test”,然后你调用repeat(2)

首先创建a = new Array(undefined, undefined, undefined); // 2 + 1次。

然后它开始加入字符串,在每对之间放置“test”。

new String(undefined) + new String("test") + new String(undefined); + new String("test") + new String(undefined)

以上变为:

"" + "test" + "" + "test" + "" = "testtest"// two times the original string.
相关问题