The slice() function of Array in javaScript

JavaScript slice() method 

Directly upload code and screenshots

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javaScript中Array(数组)的slice()函数</title>
<script type="text/javascript">
//slice()函数可从已有的数组中返回选定的元素
//Array.slice(startIndex, endIndex)
//slice()函数返回一个新的数组,包含从起始下标到结束下标(不包括该元素)的数组中的元素

//slice()函数并不会修改数组,而是返回一个子数组。如果想删除数组中的一段元素,应该使用方法 Array.splice()
var names = ['韦小宝', '建宁公主', '阿珂', '苏荃', '曾柔', '方怡', '沐剑屏', '双儿'];
console.log(names);
console.log(names.slice(1, 7));
console.log(names);
//会选取从下标2开始的位置到数组结尾的所有元素
console.log(names.slice(2));
console.log(names);

//-1指最后一个元素,-2指倒数第二个元素,以此类推
//会选取从倒数第4个元素的位置到数组结尾的所有元素
console.log(names.slice(-4));//Array(4) [ "曾柔", "方怡", "沐剑屏", "双儿" ]
//会选取从倒数第3个元素的位置到数组的下标为7的位置
console.log(names.slice(-3, 7));//Array [ "方怡", "沐剑屏" ]
//会选取从倒数第3个元素的位置到数组的下标为2的位置
console.log(names.slice(-3, 2));//Array []
console.log(names);
</script>
</head>
<body>
<h2>javaScript中Array(数组)的slice()函数</h2>
</body>
</html>

The results of the operation are as follows:

Guess you like

Origin blog.csdn.net/czh500/article/details/114555395