简体   繁体   English

为什么 is.splice(1, 0, '.') 返回一个空数组? (Javascript)

[英]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. console.log 返回一个空数组。

I want it to return '1.34'.我希望它返回“1.34”。 What am I doing wrong?我究竟做错了什么?

If you see the reference for Array.prototype.splice on mdn :如果您在mdn上看到Array.prototype.splice的参考:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容

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.在您的代码末尾,当您执行.splice(1, 0, '.')时,它会删除 0 个元素,因此它将返回一个空数组。

I'm assuming you want to get the previous array with the '.'我假设你想用'.'获取前一个数组。 element inserted in the first position.元素插入第一个 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('')如果你想把它加入一个字符串,只需使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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