数组copyWithin()方法以及JavaScript中的示例

JavaScript copyWithin()方法 (JavaScript copyWithin() method)

copyWithin() method is used to copy the specified elements from an array and replace from specified index within the same array. It changes the this array (actual array).

copyWithin()方法用于从数组中复制指定的元素,并从同一数组中的指定索引进行替换。 它将更改此数组(实际数组)。

Syntax:

句法:

    array.concat(target_index, [start_index], [end_index]);

Parameters:

参数:

  • target_index is an index in the same array to replace the elements.

    target_index是同一数组中用于替换元素的索引。

  • start_index is an optional parameter and it's default value is 0, it is used to specify the source start index to copy the elements.

    start_index是一个可选参数,默认值为0,用于指定要复制元素的源起始索引。

  • end_index is also an optional parameter and it's default value is array.lentgh, it is used to specify the source end index.

    end_index也是一个可选参数,默认值为array.lentgh ,用于指定源结束索引。

Example:

例:

    Input:
    var names = ["Manju", "Amit", "Abhi", "Radib", "Prem"];

    Function call:
    names.copyWithin(2, 0);
    
    Output:
    Manju,Amit,Manju,Amit,Abhi

JavaScript Code to demonstrate example of Array.copyWithin() method

JavaScript代码演示Array.copyWithin()方法的示例

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var names = ["Manju", "Amit", "Abhi", "Radib", "Prem"];
		
		document.write("Before function call...<br>");
		document.write("names: " + names + "<br>");
		
		//copy from 0th index and replace from 2nd index
		names.copyWithin(2);
		
		document.write("After function call...<br>");
		document.write("names: " + names + "<br>");	
		
		//another example
		var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
		
		document.write("Before function call...<br>");
		document.write("arr: " + arr + "<br>");		
		
		//copy from 1st index to 3rd and replace from 6th index
		arr.copyWithin(6,1,4);
		
		document.write("After function call...<br>");
		document.write("arr: " + arr + "<br>");				
	</script>
</body>
</html>

Output

输出量

Before function call...
names: Manju,Amit,Abhi,Radib,Prem
After function call...
names: Manju,Amit,Manju,Amit,Abhi
Before function call...
arr: 10,20,30,40,50,60,70,80,90,100
After function call...
arr: 10,20,30,40,50,60,20,30,40,100


翻译自: https://www.includehelp.com/code-snippets/array-copyWithin-method-with-example-in-javascript.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值