+ 1

JS array and input question help

In this code, - There is an input - There are 6 divs with the same class name ("a"); - array["A", "B", ....,"F"]; Through Js, I put the 6 divs' innerHTML (A, B, C, D, E, F) from the array. Now, on input, I want to test if any letters from the array match the input.value. If yes, the letter that matched.style.color = "yellow" else "white"; For example: I'm typing in the input; And I type "B", the B(div).style.color = "yellow"; ... Kind of like, you have 6 letters to type. Once you typed it it disappears. (or in this case color "yellow"); https://code.sololearn.com/WOQrI6XdD1Dd/#js

8th Nov 2019, 4:29 AM
Ginfio
Ginfio - avatar
5 odpowiedzi
+ 1
Includes() is also a String prototype method. So, in this case, your use of includes() is fine. But in order to check if any element of array is included in the input value, you need to loop over array using either Array method forEach(), filter(), or find(). You can also use plain for-loop. https://code.sololearn.com/WvF7yB01fOL0/#html With your code as-is you are only checking one element of array and according to your code that element is at index 6 of array, while there are 6 elements of array, it does not have an index 6. Thus there is no div to be found, which is the reason for the error message you are getting. btw it is white, not [whtie]😁
8th Nov 2019, 10:52 AM
ODLNT
ODLNT - avatar
+ 4
I added the following lines to your code to make the problem more obvious : console.log("line 16 : " + inp.value.includes(array[m])); console.log("line 17 : " + array.indexOf(inp.value)); https://code.sololearn.com/W5MWYLv8ClLo/?ref=app There are two mistakes. Firstly, your way of using includes() is wrong. includes() is an array prototype method, the usage is array.includes(value) Secondly, includes() is not the most suitable to use here. for your problem, you should use indexOf(). Actually, before ES6 includes() method, we compare indexOf() !== -1 to check whether the array contains the value.
8th Nov 2019, 6:42 AM
Gordon
Gordon - avatar
+ 2
Ginfio You are welcome. You just need to replace the word filter with forEach and you will get the same results.
8th Nov 2019, 8:04 PM
ODLNT
ODLNT - avatar
+ 1
ODLNT That works perfectly. I'm interested to see how we would do it using forEach(). Could you please show me how we do it using forEach() too: https://code.sololearn.com/WOQrI6XdD1Dd/?ref=app Thanks.
8th Nov 2019, 3:47 PM
Ginfio
Ginfio - avatar
+ 1
ODLNT that.works(too). Thanks again.
8th Nov 2019, 8:07 PM
Ginfio
Ginfio - avatar