N
N
Nifontov2018-07-08 11:29:18
Angular
Nifontov, 2018-07-08 11:29:18

How to add an element to an array through a function?

Good afternoon.
I need to add an element to the array after a certain time, I'm not strong in typescript.
Please, help.
i have this code

import { Component} from '@angular/core';


@Component({
  selector: 'mail-box',
  templateUrl: 'mailBox.component.html',
  styleUrls: ['./style.css']
})

export class mailBoxComponent { 

items = [1];

}

function add(i: number) {
  if (i <= 10) {
    addItem();
    setTimeout(add, 3000);
  }
}

function addItem() {
  this.items.leght + 1;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nakree, 2018-07-08
@nakree

I'm not good at typescript

Maybe in javascript?
Add element to array:
https://developer.mozilla.org/en/docs/Web/JavaScri...
https://developer.mozilla.org/en/docs/Web/JavaScri...
https://developer .mozilla.org/ru/docs/Web/JavaScri...
Read about how setTimeout works:
https://learn.javascript.ru/settimeout-setinterval
Usage example:
let items = [1];

add = (i) => {
  if (i <= 10) {
    setTimeout(() => addItem(i), 3000)
  }
}

addItem = (item) => {
  items = [...items, item]
//items = items.concat([item])
//items.push(item)
}

//проверить
test = () => {
  console.log(items)
  add(5)
  add(6)
  add(999)
  console.log(items)
  setTimeout(() => console.log(items), 3500)
}

test()

//Console:
//[1]
//[1]
//[1, 5, 6]

https://jsfiddle.net/Lhy3n2c5/18/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question