简体   繁体   中英

Array.push is not a function with return Array

Im having problem when im Inputing to my Textarea a different character. That the .push method is not a function error. I cant seem to find a Solution.

updatestats(){
           //sample input
        let input = "aab";
        let collectionresult = [];
        for(let i=0;i < input.length;i++)
        {
            let char = input[i];
            collectionresult = this.checkuniqueness(collectionresult,char);
            
        }        
        console.log(collectionresult);
    }
    checkuniqueness(collection, character) {
        let update = false;
        for (let i = 0; i < collection.length; i++) {
            if (collection[i].character === character) {
                collection = {
                    character: character,
                    number: collection[i].number + 1
                }
                update = true;
            }
        }
        if (update === false) {
            collection.push({
                character: character,
                number: 1
            });

        }

        return collection;
    }

In the first function you set the collection variable to be an array but in the second function you are changing the type of the 'collection' variable to be an object but push() is only defined for arrays, so this cannot work :

    collection = {
        character: character,
        number: collection[i].number + 1
    }

As others have pointed out, you're replacing the collections array with a single object containing the updated element for the given character. You should just update that element in place rather than reassign the array itself by replacing that assignment with:

collections[i].number++;

Your function can also be simplified by replacing the loop with the find() method.

checkuniqueness(collection, character) {
  let counter = collection.find(o => o.character == character);
  if (counter) {
    counter.number++;
  } else {
    collection.push({
      character: character,
      number: 1
    });
  }

  return collection;
}

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