1
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.

4
  • @NewToJS Your name is accurate; .split() returns an array Commented Feb 3, 2017 at 15:56
  • You are aware of the + operator in JavaScript, aren't you? Your code looks like it is for a write-code-that-is-impossible-to-read contest ;) Commented Feb 3, 2017 at 15:57
  • 1
    You're right, save for the two console statements, two lines of script is damn near impossible to read. Thanks for answering my question @str Commented Feb 3, 2017 at 15:59
  • I did not say that I don't understand the individual commands. But I have absolutely no clue what you are up to by converting an integer to a string, then to an array, then trying to change a single array item, and then cast the whole thing back to a string again. Just because it is possible doesn't make it good, understandable code. Commented Feb 3, 2017 at 16:02

3 Answers 3

5

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.