javascript - 在javascript中将数组中的单个字符与字符串连接起来?

标签 javascript arrays string concatenation

大家好,我有一个问题。我试图将数组中的单个值与字符串连接起来,但它没有连接。

示例

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/

相关文章:

javascript - 在 jQuery 对话框中显示布局

arrays - Scala,数组总是按名称调用,对吧?

c - 为什么 *(ptr++) 不给出数组中的下一项?

iphone - localizedNameOfStringEncoding 不起作用

c++ - 在尊重 BOM 的同时匹配 Unicode 代码点的约定?

javascript - 生成pdf支持阿拉伯语

javascript - ES6 中的惰性模块加载是如何工作的

javascript - 用于 Node.js 的 ZeroMQ 是否与 Electron 兼容?

javascript - 如何将对象中的字符串值转换为数字?

javascript - 如果域匹配,则将纯 URL 替换为链接