Home >Web Front-end >JS Tutorial >The easiest way to clone an array in JavaScript_javascript tips

The easiest way to clone an array in JavaScript_javascript tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 18:55:551242browse

var a = [1, 2, 3];
var b = a.slice(0);
b[1] = 20;
alert(a[1]); //->2
alert(b[1]); //->20
If the two values ​​are different, it means the cloning is successful. Of course, you can also use the Array prototype:
Array.prototype.clone = function () {
return this.slice(0);
}
var a = [1, 2, 3 ];
var b = a.clone();
b[1] = 20;
alert(a[1]); //->2
alert(b[1]) ; //->20

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn