基于长度的中间值的切片法

问题描述 投票:0回答:1

使用 slice 方法,字符串的长度为 2; 这为奇数字符串数组提供了一个 float,为偶数字符串数组提供了一个整数。

我想了解更多关于字符串长度的分片方法的工作背景。Fiveo2.5;

function sliceMiddle(s) {
  console.log(s.length)
  console.log(s.slice((s.length - 1) / 2, s.length / 2 + 1));
}
sliceMiddle("Fiveo");
javascript integer slice string-length
1个回答
0
投票

这里是文档 关于如何 slice() 的工作。

你可能想使用 Math.ceil()Math.floor() 以获得一个整数位置,将奇数长度的字符串切到你想要的位置(可以在中间字符之后或之前)。

console.log(Math.ceil(2.5));
console.log(Math.floor(2.5))

0
投票

任何 value 传给 slice(begin, end),javascript会尽最大努力尝试将 无论如何 输入它被赋予一个整数。参见 此处.

用于转换 beginend 到整数的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
© www.soinside.com 2019 - 2024. All rights reserved.