Home > Enterprise >  Javascript: Push a word into array only if the array doesn't have that word already?
Javascript: Push a word into array only if the array doesn't have that word already?

Time:11-17

im trying to create a game where every time you enter a word into text field and press "Play", functions checks an array for the word you typed, if it is not there it will push it, if it is already there it will produce an error. I can't figure out what is wrong. Been at it for hours.

I know i need to create an empty array where words will be stored, and i need to loop through the array and write an if statement basically saying if array item does not equal to the field value then push it into array otherwise display an error message. It seems like a simple problem but i can't figure out what i am doing wrong.

The next part of the game, i will have to only push a word that is not in the array and it also has to start with the same name that the last word in the array ended on. But i am not there yet.

Thank you so much for your help.

HTML

<body>
   
    <div id="main-container">
    
    <input type="text" id="field" >
    <div id="message"></div>
    <button  id="play">Play</button>
    
</div>


    <script src="index.js"></script>
</body>
JS

const field = document.querySelector('#field');
const message = document.querySelector('#message');
const playBtn = document.querySelector('#play')


let usedCities = ['york']

playBtn.addEventListener('click', function() {
    let fieldView = field.value;
    


    for (let i = 0; i < usedCities.length; i  ) {
       if (usedCities[i] !== fieldView) {
        usedCities.push(fieldView) 
       } else {
        message.textContent = "ERROR"
       }
        
        
    }

    
})

This is basically as far as I got but it doesn't work.

Thank you so much.

CodePudding user response:

You can check for array values with array.includes

const usedCities = ['Copenhagen'];
const fieldView = 'Copenhagen';

if(!usedCities.includes(fieldView)){
    usedCities.push(fieldView)
}

console.log(usedCities);

Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

  • Related