Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.prototype.copyWithin 的 用法 #50

Open
lovelmh13 opened this issue Nov 15, 2020 · 0 comments
Open

Array.prototype.copyWithin 的 用法 #50

lovelmh13 opened this issue Nov 15, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

会改变数组本身的 api之一,但是不会改变数组的 length

因为 copyWithin 会把指定的自身的一段数组复制给自身要被替换的位置。

两个参数的情况

var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(0, 4) // [5, 6, 3, 4, 5, 6]
var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(0, 2) // [3, 4, 5, 6, 5, 6]
var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(1, 2) // [1, 3, 4, 5, 6, 6]
var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(4, 3) // [1, 2, 3, 4, 4, 5]

从上面四个例子,可以看出,第一个参数是要被替换的起始位;第二个参数,是从哪个 index 开始复制,并且一直复制到数组结尾。

三个参数的情况

var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(0, 1, 2) // [2, 2, 3, 4, 5, 6]
var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(1, 3, 5) // [1, 4, 5, 4, 5, 6]
var a = [1, 2, 3, 4, 5, 6]
a.copyWithin(1, 3, 2) // [1, 2, 3, 4, 5, 6]

从上面三个例子,可以看出,第三个参数是复制截取到的 index 的地方,并且不算 index 本身。如果比第二个参数小,则不起作用

再配合 MDN 的文档看,就清晰了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant