一、字符串转数组: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) |