Array.splice does not work as expected

3

For example:

var frutas = ["goiaba", "manga", "laranja", "abacate"];
frutas.splice(1, 1);

This code, instead of removing 1 item from the second index of my array (1), only returns the item I want to delete, which in this case is "orange";

That is, instead of returning ["goiaba", "manga", "abacate"] - it returns ["laranja"] ;

As I understood what I read / researched, Array.prototype.splice() serves to do what I'm trying to do. Am I right? If yes, why is this behavior of the splice method?

NOTE: Google Chrome browser version 60

    
asked by anonymous 19.09.2017 / 04:07

1 answer

3

The splice method is a general-purpose method for inserting elements into an array, removing elements from an array, or performing both operations at the same time.

The first argument of splice specifies the position of the array where insertion or deletion should begin.

The second argument specifies the number of elements that should be excluded.

The first two arguments of splice specify which array elements to exclude. These arguments can be followed by any number of additional arguments, specifying the elements to be inserted into the array, starting at the position specified by the first argument.

See how it works:

var frutas = ["goiaba", "manga", "laranja", "abacate"];
//remove 1 elemento posição 1 (remove manga) 
var frutasRemovida = frutas.splice(1, 1);

var nomes = ["Leo", "inova pixel", "Anderson Carlos Woss", "fernandoandrade", "mengano",  "fulano", "ciclano", "beltrano", "sicrano"];
//remove 3 elementos começando da posição 2 (remove Anderson Carlos Woss, fernandoandrade e mengano) 
var nomesRemovidos = nomes.splice(2, 3);

console.log(frutas);

console.log(frutasRemovida);

console.log(nomes);

console.log(nomesRemovidos);

Now notice this example:

var numeros = [1, 2, 3, 4, 5];
//remove 1 elemento começando da posição 3 e inclui os elementos "a" "b" a começando da posição 3 
var add = numeros.splice(3,1,"a","b");

console.log(numeros);
console.log(add);

Plus this

var numeros = [1, 2, 3, 4, 5];
var add = numeros.splice(2,2,"a","b","c","[123asd]");

console.log(numeros);
console.log(add);
    
19.09.2017 / 05:05