Javascript-数组输入的每个字母

时间:2018-12-08 10:22:40

标签: javascript html arrays

我有一个输入类型为maxlength = 5的文本,如下所示:

<input id="word" type="text" name="word" maxlength="5">
<button id="btn"> Send </button>

有没有办法接收输入并将每个字母分隔到数组的每个索引?

示例:

input= "carro";
array=["c","a","r","r","o"]

我知道如何将输入放入数组,但不能像这样分开。 谁能帮我吗?

2 个答案:

答案 0 :(得分:3)

在JS中通常有不止一种方法。 我知道从字符串中获取数组的3种方法。

  1. 使用.split和空白字符串作为参数。 但是,正如@georg所述,“它不适用于32位字符,例如emojis”。

  2. 使用Array对象的方法.from

  3. 或最新方法:结合.of的另一种方法spread syntax

<input id="word" type="text" name="word" maxlength="5" value="carro">
<button id="btn"> Send </button>
<script>
  document.querySelector('#btn').addEventListener('click', function() {
    const value = document.querySelector('#word').value

    // const array = value.split('')
    // const array = Array.from(value)
    const array = Array.of(...value)
    console.log(array)
  })
</script>

答案 1 :(得分:1)

split方法将有助于解决您的问题

document.getElementById('btn').onclick = function(){
    var input =document.getElementById('word').value;
    var val = input.split('');
    console.log(val);
}
<input type='text' id='word' value='carro'>
<button id='btn'>Send</button>