大家好,我有一个问题。我试图将数组中的单个值与字符串连接起来,但它没有连接。
示例
arr[] => ['R','b','c']
string => "am"
我想 arr[0] + string 即,将数组的第一个索引值连接到字符串。
如何在不更改数组或字符串的数据类型的情况下执行此操作,只需将数组连接到字符串。
编辑:这是代码
function rotate() {
var string = document.getElementById("string").value
var str_arr = string.split();
document.getElementById("string").value = str_arr[string.length - 1] + string.substring(0, string.length - 1);
}
<fieldset>
<label for="name">String:</label>
<input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="rotate()">Rotate</button>
最佳答案
要反转字符串,请将其拆分为数组,旋转数组并将其连接回字符串。
function check(){
var string = document.getElementById("string").value;
document.getElementById("string").value = string.split('').reverse().join('');
}
<fieldset>
<label for="name">String:</label>
<input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="check()">Rotate</button>
要移动字符串开头的最后一个字符,请使用子字符串:
function check(){
var string = document.getElementById("string").value;
document.getElementById("string").value = string.substr(string.length - 1) + string.substr(0, string.length - 1);
}
<fieldset>
<label for="name">String:</label>
<input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="check()">Rotate</button>
关于javascript - 在javascript中将数组中的单个字符与字符串连接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43936024/