gpt4 book ai didi

javascript - 如何使用 JavaScript 通过子字符串获取 ymd

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:11 25 4
gpt4 key购买 nike

用这段代码获取ymd:

var ymd = '20190716';
var year = ymd.substring(0, 4);
var month = ymd.substring(4, 2);
var day = ymd.substring(6, 2);

console.log(year);
console.log(month);
console.log(day);

我认为这是从索引到长度获取子字符串的正确方法。所以……

想要:

2019
07
16

但是得到了:

2019
19
1907

为什么?

最佳答案

检查 docs :

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped.

所以当您传递 4, 26, 2 时,您是说您希望结束索引开始索引,所以参数被切换,你得到索引 2 到 4,索引 2 到 6。

也许您想要 substr,它可以满足您的期望:

The arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the number of characters to include in the returned string.

var ymd = '20190716';
var year = ymd.substr(0, 4);
var month = ymd.substr(4, 2);
var day = ymd.substr(6, 2);
console.log(year);
console.log(month);
console.log(day);

但它(有点)被弃用了。我更喜欢 substringslice,并传递索引。

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice() method returns an empty string if this is the case.

slice 的行为在我看来更直观一些。

关于javascript - 如何使用 JavaScript 通过子字符串获取 ymd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57052839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com