首页 > 解决方案 > 我如何从用户那里获取输入报价并将其打乱,然后将每个字母分开放在 JavaScript 的表格中

问题描述

我有以下打字稿。

它应该随机化用户输入的报价

quoteReady: boolean = false;

randomizQuote(array);

{
  this.quoteReady = true;

  this.quote = array;

  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

2.这就是我在 html 中输入的内容,我想做的是随机引用并在每个表中放入 2 到 3 个字母

<section *ngIf="quoteReady">
  <table class="table table-bordered table-hover table-responsive">
    <thead>
      <td>
        <tr *ngFor="let quo of quote">{{ citation }}</tr> //i want to insert a
        randome 2 to 3 //letters from the quote here
      </td>

      <td>
        <tr *ngFor="let quo of quote">{{ array }}</tr>
      </td>

      <td>
        <tr *ngFor="let quo of quote">{{ array }}</tr>
      </td>

      <td>
        <tr *ngFor="let quo of quote">{{ array }}</tr>
      </td>

      <td>
        <tr *ngFor="let quo of quote">{{ array }}</tr>
      </td>
    </thead>
  </table>
</section>

所以,我不确定为什么这没有给出输出。

标签: javascriptangular

解决方案


基于这个答案

你可以在你的ts

import { Component, VERSION, OnInit} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
randomQuote = [];
numberOfLetters = 3
quote = "abcdefghijklmonopqrstuwxyz".split('');
quoteIndexes = {}

 ngOnInit(){
  while (this.randomQuote.length < this.numberOfLetters){
    let index = -1;
    do {
      index = Math.floor(Math.random() * this.quote.length);
      this.quoteIndexes[index] = true;
    } while (!(index in this.quoteIndexes))
    this.randomQuote.push(this.quote[index]);
  }
 }
}

然后

<td>
  <tr *ngFor='let letter of randomQuote'>{{letter}}</tr>
</td>

在这里,您绝对需要有一个小于或等于引号长度的字母,还要确保避免使用空引号

stackBlitz 演示


推荐阅读