在 JavaScript 中使用 slice()

Using slice() in JavaScript

我很难理解 slice() 与以下代码的用法,它无法获取我预期的结果。

var cDate = "11-05-2016";
var m = cDate.slice(0,2);
var d = cDate.slice(3,2);
var y = cDate.slice(6);
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

这给出了以下输出:

Month is 11
Day is 
Year is 2016

我尝试 slice 使用不同的字符串。但是每次我这样做时,当我从字符串的中间切出它时,它总是给我一个空字符串。这是为什么?

您似乎混淆了 slicesubstr。参数的含义不同:

  • slice( startIndex, endIndex )
  • substr( startIndex, length )

var cDate = "11-05-2016";
var m = cDate.substr(0,2); // "11"
var d = cDate.substr(3,2); // "05"
var y = cDate.substr(6); // "2016"
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

来自MDN

The slice() method extracts a section of a string and returns a new string.

切片的语法是:

str.slice(beginSlice[, endSlice])

请注意 endSlice 是字符串中的实际位置(并且 不是 beginSlice 中获取多少个字符)。

在您的示例中 - 您无法将字符串从位置 3 分割到位置 2(因为它向后移动),因此您得到一个空字符串。