简体   繁体   中英

Array not returning any value using console log

I'm trying to create a program that can shuffle the middle letters (that is, all letters except the first and last letter in the word) within words. I am trying to pull words out of a string, that is pasted into a text area, in my HTML document, and create an array out of them. From there I'll figure out how to somehow make the shuffling works --but for now my problem is as follows:

 const text = document.getElementById('textfield'); const textstring = JSON.stringify(text); document.querySelector('form.input-form').addEventListener('submit', function (e) { e.preventDefault(); console.log(text.value); var a1 = new Array(); a1 = textstring.split(' '); console.log(a1); });
 <.doctype html> <html> <head> <title>omrokering af bogstaver</title> <meta charset="utf-8"> </head> <body id="body"> <form class="input-form"> <input id="textfield" type="text" placeholder="Paste text" /> <button type="submit">omrokér</button> </form> <script type="text/javascript" src="omrokering.js"></script> </body> </html>

I can successfully pull the code out of the form, but when I try to log the contents of the array (I have tried a lot of different ways), it prints this: (1) ['{}'] in the console log, after I've typed in the textarea. When I use this alert function:

if(textstring !== null){alert(null);}

It returns "null", so I'm assuming the array is empty, and there is a problem with pulling the string from the form into the array.

I'm very beginner, so it will be greatly appreciated if you can give me a good explanation for this along with a solution, thank you!

 const text = document.getElementById('textfield'); document.querySelector('form.input-form').addEventListener('submit', function (e) { e.preventDefault(); console.log(text.value); var a1 = text.value.split(' '); console.log(a1); });
 <form class="input-form"> <input id="textfield" type="text" placeholder="Paste text"> <button type="submit">omrokér</button> </form> <script src="omrokering.js"></script>

Remove textstring that is unnecessary and don't stringify() as it's already a string; and use text element only which you already console.log().

 const text = document.getElementById('textfield'); document.querySelector('form.input-form').addEventListener('submit', function (e) { e.preventDefault(); console.log(text.value); console.log(text.value.split(' ')); });
 <.doctype html> <html> <head> <title>omrokering af bogstaver</title> <meta charset="utf-8"> </head> <body id="body"> <form class="input-form"> <input id="textfield" type="text" placeholder="Paste text" /> <button type="submit">omrokér</button> </form> <script type="text/javascript" src="omrokering.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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