Javascript新的数组功能

Javascript新的数组功能,javascript,prototype,Javascript,Prototype,我在一个网站上看到了下面的代码,我无法理解被评论为“怀疑”的那句话。 函数如何使用“newarray(n+1).join(this)”返回重复的文本 当您通过参数str连接n长度的数组时,您将通过插入str的n-1项来创建一个新字符串,这样每个数组项之间就有一个字符串。例如: const arr = ['foo', 'bar', 'baz']; arr.join(' ') // results in // foo bar baz 新数组(n+1)创建一个长度为n+1但没有元素的数组。当这些不存

我在一个网站上看到了下面的代码,我无法理解被评论为“怀疑”的那句话。 函数如何使用“newarray(n+1).join(this)”返回重复的文本


当您通过参数
str
连接
n
长度的数组时,您将通过插入
str
n-1
项来创建一个新字符串,这样每个数组项之间就有一个字符串。例如:

const arr = ['foo', 'bar', 'baz'];
arr.join(' ')
// results in
// foo bar baz
新数组(n+1)
创建一个长度为
n+1但没有元素的数组。当这些不存在的元素被
.join
转换为字符串时,将生成空字符串

String.prototype.repeat中的
this
是调用函数的字符串。例如:

'foo'.repeat(
结果为
String.prototype.repeat
调用
this
'foo'

因此:

结果生成一个新字符串,该字符串包含
n
重复的
this

另一种方法是,如果调用了
'x'。repeat(2)
,则构造以下数组:

// [<empty>, <empty>, <empty>]
// insert 'x' between each element of the array:
// '' + 'x' + '' + 'x' + ''
// result: 'xx'
/[,]
//在数组的每个元素之间插入“x”:
//'+'x'+'+'x'+''
//结果:“xx”

我是蒂格兰,我可以回答你的问题

字符串类中有一个重复方法:

 if (!String.prototype.repeat) { 
  String.prototype.repeat = function(n) {
     //some code
  }
}
这是一个给定的字符串(在本例中为“La”):

让我们用“La”字符串来讨论,
“La”。重复(3)
这个
是“La”,n是3。
新阵列(3+1)
->
[empty×4]
[,,,]连接('La')
->
“LaLaLa”
(,->空) join是通过给定字符串将数组转换为字符串的方法。
如果有任何问题,请随时提问。

换句话说,使用分隔符加入
null
values
n
times
foo
// [<empty>, <empty>, <empty>]
// insert 'x' between each element of the array:
// '' + 'x' + '' + 'x' + ''
// result: 'xx'
 if (!String.prototype.repeat) { 
  String.prototype.repeat = function(n) {
     //some code
  }
}
return new Array(n + 1).join(this);