简体   繁体   中英

Why is .splice(1, 0, '.') returning an empty array? (Javascript)

Here is my code:

 let num = 0.0134; console.log(num.toString().split('').splice(3).splice(1, 0, '.'))

The console.log returns an empty array.

I want it to return '1.34'. What am I doing wrong?

If you see the reference for Array.prototype.splice on mdn :

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

Return Value: An array containing the deleted elements.

At the end of your code, when you do .splice(1, 0, '.') , it deletes 0 elements so it will return an empty array.

I'm assuming you want to get the previous array with the '.' element inserted in the first position. For that you'll want to do:

const arr = num.toString().split('').splice(3);
arr.splice(1, 0, '.');
console.log(arr)

And If you want to join it to a string just use arr.join('')


Anyway, for your use case, you could just use the * multiplication operator rather than converting to a string array and attempting to manipulate that.

You can simply do:

let num = 0.0134;
console.log(num * 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM