简体   繁体   English

从数组中的单个字符与JavaScript中的字符串连接?

[英]concatenate single character from an array with string in javascript?

Hey everyone I have one problem. 大家好,我有一个问题。 I am trying to concatenate a single value from array with the string but it is not concatenating. 我正在尝试使用字符串将数组中的单个值连接起来,但未连接在一起。

Example

arr[] => ['R','b','c']
string => "am"

I want to arr[0] + string ie., concatenate first index value of array to string. 我想arr [0] +字符串,即,将数组的第一个索引值连接到字符串。

How can I do this without changing the data type of array or string just concatenate array to string. 我如何做到这一点而无需更改数组或字符串的数据类型,而只需将数组连接到字符串即可。

Edit: Here is the code 编辑:这是代码

 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> 

To reverse a string split it into array, rotate array and join it back to a string. 要反转字符串,请将其拆分为数组,旋转数组并将其重新连接回字符串。

 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> 

To move last character in beginning of a string use substrings: 要在字符串的开头移动最后一个字符,请使用子字符串:

 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> 

You can achive this using charAt() function. 您可以使用charAt()函数来实现。

function rotate(){ 函数rotate(){

var string = document.getElementById("string").value var str_arr = string.split(); var string = document.getElementById(“ string”)。value var str_arr = string.split(); document.getElementById("string").value = string.charAt(string.length - 1) + string.substring(0, string.length - 1); document.getElementById(“ string”)。value = string.charAt(string.length-1)+ string.substring(0,string.length-1);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM