简体   繁体   English

Array.push 不是返回数组的函数

[英]Array.push is not a function with return Array

Im having problem when im Inputing to my Textarea a different character.我在向我的 Textarea 输入不同字符时遇到问题。 That the .push method is not a function error. .push 方法不是函数错误。 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 :在第一个函数中,您将集合变量设置为数组,但在第二个函数中,您将“集合”变量的类型更改为对象,但 push() 仅针对数组定义,因此无法正常工作:

    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.正如其他人指出的那样,您正在用包含给定字符的更新元素的单个对象替换collections数组。 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.您还可以通过用find()方法替换循环来简化您的函数。

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

  return collection;
}

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

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