使用 slice 方法,字符串的长度为 2; 这为奇数字符串数组提供了一个 float,为偶数字符串数组提供了一个整数。
我想了解更多关于字符串长度的分片方法的工作背景。Fiveo
是 2.5
;
function sliceMiddle(s) {
console.log(s.length)
console.log(s.slice((s.length - 1) / 2, s.length / 2 + 1));
}
sliceMiddle("Fiveo");
这里是文档 关于如何 slice()
的工作。
你可能想使用 Math.ceil()
或 Math.floor()
以获得一个整数位置,将奇数长度的字符串切到你想要的位置(可以在中间字符之后或之前)。
console.log(Math.ceil(2.5));
console.log(Math.floor(2.5))
任何 value
传给 slice(begin, end)
,javascript会尽最大努力尝试将 无论如何 输入它被赋予一个整数。参见 此处.
用于转换 begin
和 end
到整数的javascript这样做。
返回与number同号的数字值,并且其大小是floor(abs(number))。
所以,在这种情况下会发生这些事情。
str.slice(1, 3) // from index 1 to 2
str.clice(1, 3.1) // from 1 index to 2
str.slice(1, 3.9) // from 1 index to 2
str.slice(1.1, 3) // from index 1 to 2
str.clice(1.9, 3) // from 1 index to 2