1

I have an array of number, I want to calculate the square of numbers and display them in list. Right now I am calculating squares separately and rendering them separately using map function as follows

var arr = [1, 2, 3, 4, 5];
for (var i = 0; i < arr.length; i++) {
  arr[i] = arr[i] * arr[i];
}

render() {
  return html`<ul>
    ${arr.map(item => html`<li>${item}</li>`)}
  </ul>`;
}

Is there a way such that the operations are performed with map function. I am new to using map function.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
gita 98
  • 53
  • 2

3 Answers3

2
let arr=[1,2,3,4,5];

render(){
return html`<ul>
${arr.map(item => html`<li>${item * item}</li>`)}
</ul>`
}
0

You can do the square operation inside the arr.map in `render function.

var arr = [1, 2, 3, 4, 5];
render() {
  return html `<ul>
    ${arr.map(item => html`<li>${item * item}</li>`)}
  </ul>`
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

You can use Math.pow() to do calculation

let arr=[1,2,3,4,5];

render(){
return html`<ul>
${arr.map(item => html`<li>${Math.pow(item, 2)}</li>`)}
</ul>`
}
Damien
  • 1