猿问

显示对象模板角度,计算重复单词的数量

我想显示 Object wordCounts,它存储一系列单词,其值是一个单词在字符串中重复的次数,发生的情况是我想按该单词的重复次数按顺序显示该变量有,我只想显示 20 个重复次数最多的单词。我遇到的主要问题是,就我的代码而言,它返回一个 JSON,这不允许我放入一个 div 来给它一个样式。


项目详情.ts


getWordCount(str) {

let arrayOfWords = str.split(/\s+/);


var wordCounts = Object.create(null);


for(let i = 0; i<arrayOfWords.length; i++){

  let word = arrayOfWords[i];


  if(!wordCounts[word]){

    wordCounts[word] = 1;

  }else{

    wordCounts[word] ++;

  }

}

    return wordCounts;  

};

项目详细信息.html


 <p>{{getWordCount(str) | keyvalue | json}}</p>

表示


[ { "key": "También", "value": 1 }, { "key": "Un", "value": 1 }, { "key": "algoritmo", "value": 1 }, { "key": "aunque", "value": 1 }, { "key": "caracteres", "value": 1 }, { "key": "cifrado", "value": 1 }, { "key": "codificados", "value": 1 }, { "key": "composición", "value": 2 }, { "key": "cualquier", "value": 1 }, { "key": "de", "value": 5 }, { "key": "descifrado", "value": 1 }, { "key": "destinatario", "value": 1 }, { "key": "en", "value": 1 }, { "key": "es", "value": 2 }, { "key": "escritura", "value": 1 }, { "key": "forma", "value": 1 }, { "key": "generados", "value": 1 }, { "key": "imprimibles", "value": 1 }, { "key": "no", "value": 1 }, { "key": "original.", "value": 1 }, { "key": "para", "value": 1 }, { "key": "persona,", "value": 1 }, { "key": "por", "value": 2 }, { "key": "puede", "value": 1 }, { "key": "que", "value": 1 }, { "key": "que,", "value": 1 }, { "key": "sentido", "value": 1 }, { "key": "sentido.", "value": 1 }, { "key": "ser", "value": 1 }, { "key": "signos", "value": 1 }, { "key": "sistema", "value": 1 }, { "key": "su", "value": 1 }, { "key": "sí", "value": 1 }, { "key": "texto", "value": 1 }, { "key": "tienen", "value": 1 }, { "key": "un", "value": 2 }, { "key": "una", "value": 3 }, { "key": "unidad", "value": 1 } ]

结果我不能给它任何风格。


温温酱
浏览 147回答 2
2回答

慕田峪4524236

您可以将值分配给变量,删除json管道并直接在 HTML 中循环值。尝试以下控制器export class WordComponent {&nbsp; wordCount: any;&nbsp; getWordCount(str) {&nbsp; &nbsp; let arrayOfWords = str.split(/\s+/);&nbsp; &nbsp; let wordCounts = Object.create(null);&nbsp; &nbsp; for(let i = 0; i < arrayOfWords.length - 1; i++){&nbsp; &nbsp; &nbsp; let word = arrayOfWords[i];&nbsp; &nbsp; &nbsp; wordCounts[word] ? wordCounts[word]++ : wordCounts[word] = 1;&nbsp; &nbsp; }&nbsp; &nbsp; return wordCounts;&nbsp;&nbsp;&nbsp; };&nbsp; onMouseUp(str: string) {&nbsp; &nbsp; this.wordCount = this.getWordCount(str);&nbsp; }}模板<button (mouseup)="onMouseUp('str')">Get word count</button><ng-container *ngIf="wordCount">&nbsp; <p class="style" *ngFor="let word of wordCount | keyvalue">{{ word.key }} : {{ word.value }}</p></ng-container>然后,您可以根据需要修改和渲染。还要注意循环条件应该是arrayOfWords.length - 1因为索引从零开始。

至尊宝的传说

听起来您需要一个ShowWordCounts组件,它将您的对象作为一个@Input并生成相应的模板。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答