Nyarlat-hotep
Nyarlat-hotep

Reputation: 41

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.

Upvotes: 1

Views: 4203

Answers (3)

Michael Maaß
Michael Maaß

Reputation: 104

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"]

Upvotes: 5

Andy Stannard
Andy Stannard

Reputation: 1713

splice does not return an array just adds it into the existing array:

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

var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
var numberArray = calculation.toString().split('')

numberArray.splice(2, 0, "9");
console.log(numberArray);

Upvotes: 0

Feathercrown
Feathercrown

Reputation: 2591

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);
stringCalc.splice(2, 0, "9");
console.log(stringCalc);

splice() returns the items taken out (in this case none), not the array after the splice takes place.

Upvotes: 0

Related Questions