Search code examples
javascriptarrayssplice

Array splice removes all elements from array


var currentAge = 26;
var maxAge = 100;
var amountPerDay = 30.50;

var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
console.log(calculation);
var stringCalc = calculation.toString().split('').splice(2, 0, "9");
console.log(stringCalc);

console.log(stringCalc) shows an empty array. Does this have something to do with the toString method?

Note: I am trying to add the string "9" into the middle of the array, not remove anything from the array.


Solution

  • The missing link in your understanding is the return value of splice, which are the deleted items.

    var currentAge = 26;
    var maxAge = 100;
    var amountPerDay = 30.50;
    
    var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
    console.log(calculation);
    var stringCalc = calculation.toString().split('');
    console.log(stringCalc);
    // ["8", "2", "3", "8", "0", "5"]
    console.log(stringCalc.splice(2, 0, "foo"));
    // [] because no items were deleted, return value = array of deleted items
    console.log(stringCalc)
    // ["8", "2", "foo", 3", "8", "0", "5"]