数组常用的方法三

一、字符串转数组:split() 数组结构

用于把一个字符串分割成字符串数组。

提示: 如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。

注意: split() 方法不改变原始字符串。

<body>

<p id="demo">单击按钮显示分割后的数组.</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="How are you doing today?";
	var n=str.split(" ");
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>

菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_split

二、数组拼接:concat()

用于连接两个或多个字符串。

该方法没有改变原有字符串,但是会返回连接两个或多个字符串新字符串。

<body>

<p id="demo">单击按钮连接两个字符串成新的字符串。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var txt1 = "Hello "; //["1","2"]
	var txt2 = "world!"; //["3"]
	var n=txt1.concat(txt2);
	document.getElementById("demo").innerHTML=n; //1,2,3
}
</script>

</body>

菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_concat_string

三、数组拷贝:copyWithin(target,start,end) 从start 开始(包含)到end结束(不包含) 复制到 target

用于从数组的指定位置拷贝元素到数组的另一个指定位置中。

<body>

<p>点击按钮复制数组的前面两个元素到后面两个元素上。</p>

<button onclick="myFunction()">点我</button>

<p id="demo"></p>

<p><strong>注意:</strong> IE 11 及更早版本不支持 copyWithin() 方法。</p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {  
    document.getElementById("demo").innerHTML = fruits.copyWithin(2,0);
}
</script>

</body>

菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_copywithin

参数描述
target必需。复制到指定目标索引位置。
start可选。元素复制的起始位置。
end可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。

四、数组填充:fill()

用于将一个固定值替换数组的元素。

<body>

<p>点击按钮使用 “Runoob” 填充所有数组元素。</p>

<button onclick="myFunction()">点我</button>

<p id="demo"></p>

<p><strong>注意:</strong> IE 11 及更早版本不支持 fill() 方法。</p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {  
    document.getElementById("demo").innerHTML = fruits.fill("Runoob");
}
</script>

</body>

菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_fill

参数描述
value必需。填充的值。
start可选。开始填充位置。
end可选。停止填充位置 (默认为 array.length)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五毒幽泉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值