简体   繁体   English

Javascript-数组输入的每个字母

[英]Javascript - Each letter of an input to an array

I have an input type text with maxlength=5, like this: 我有一个maxlength = 5的输入类型文本,如下所示:

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

Is there any way to receive the input and separate each of the letters to each index of an array? 有什么方法可以接收输入并将每个字母分隔到数组的每个索引吗?

Example: 例:

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

I know how to put the input in the array but not separated like this. 我知道如何将输入放入数组,但不能像这样分开。 Can anyone help me? 谁能帮我?

There are usualy more than one way to do something in JS. 在JS中,通常有不止一种方法来做某事。 I know 3 ways to get an array from a string. 我知道从字符串中获取数组的3种方法。

  1. Use .split with blank string as an argument. 使用.split和空白字符串作为参数。 But, as @georg mentioned, "it doesn't work with 32-bit characters, eg emojis". 但是,正如@georg所述,“它不适用于32位字符,例如表情符号”。

  2. Use method .from of Array object. 使用Array对象的.from方法。

  3. Or newest way: another method .of in combination with spread syntax . 或者最新方法:一种方法.of与组合传播语法

 <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> 

split method will be useful to fix your issue 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> 

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

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