Does it mutate?

Publikováno: 18.1.2019

This little site by Remy Sharp's makes it clear whether or not a JavaScript method changes the original array (aka mutates) or not.

I was actually bitten by this the other day. I needed the last element from an array, so I remembered .pop() and used it.

const arr = ["doe", "ray", "mee"];
const last = arr.pop();
// mee, but array is now ["doe", "ray"]

This certainly worked great right away, but I didn't realize the original array had changed … Read article

The post Does it mutate? appeared first on CSS-Tricks.

Celý článek

This little site by Remy Sharp's makes it clear whether or not a JavaScript method changes the original array (aka mutates) or not.

I was actually bitten by this the other day. I needed the last element from an array, so I remembered .pop() and used it.

const arr = ["doe", "ray", "mee"];
const last = arr.pop();
// mee, but array is now ["doe", "ray"]

This certainly worked great right away, but I didn't realize the original array had changed and it caused a problem. Instead, I had to find the non-mutating alternative:

const arr = ["doe", "ray", "mee"];
const last = arr.slice(-1);
// mee, arr is unchanged

Related: Array Explorer

Direct Link to ArticlePermalink

The post Does it mutate? appeared first on CSS-Tricks.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace