gpt4 book ai didi

Javascript 处理日期的显示问题

转载 作者:行者123 更新时间:2023-11-29 23:19:21 25 4
gpt4 key购买 nike

Web 开发人员经常使用 JavaScript 来完成他们网站上的常见任务。在本教程中,我们将向您展示前 10 个可以通过剪切和粘贴在网页上使用的 JavaScript 片段!在本文中,我们将介绍以下流行的脚本片段!

<SCRIPT LANGUAGE="JavaScript">
var now = new Date();

var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();

function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())) ;

document.write(today);
</script>

最佳答案

在这两个函数中,您都需要计算下一个位置,所以我将其分成一个函数:

applyInstuction : Char -> Location -> Location
applyInstuction instruction loc =
case instruction of
'>' ->
{ loc | x = loc.x + 1 }

'^' ->
{ loc | y = loc.y + 1 }

'<' ->
{ loc | x = loc.x - 1 }

'v' ->
{ loc | y = loc.y - 1 }

_ ->
loc

基本上,它获取一个位置并根据指令计算下一个位置。

计算最终位置

然后 calculateFinalLocation 可以这样实现:

calculateFinalLocation : Location -> String -> Location
calculateFinalLocation { x, y } instructions =
List.foldl applyInstuction { x = 0, y = 0 } <| String.toList instructions

如果您不熟悉 foldl(还有 foldr)- 您可以在此处查看,例如:https://www.brianthicks.com/guide/functional-sets/4-and-a-half/ .它类似于 JavaScript 中的 map-reduce

计算第一个交点

接下来我们可以使用 Set ( http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Set ) 实现 calculateFirstIntersection。 Set 将存储我们已经访问过的位置。这是代码:

calculateFirstIntersection : String -> Maybe Location
calculateFirstIntersection instructions =
.result <|
List.foldl
(\instruction { visited, loc, result } ->
case result of
Nothing ->
let
nextVisited =
Set.insert ( loc.x, loc.y ) visited

nextLoc =
applyInstuction instruction loc
in
if Set.member ( loc.x, loc.y ) visited then
{ visited = nextVisited
, loc = nextLoc
, result = Just loc
}
else
{ visited = nextVisited
, loc = nextLoc
, result = Nothing
}

_ ->
{ visited = visited
, loc = loc
, result = result
}
)
{ visited = Set.empty, loc = { x = 0, y = 0 }, result = Nothing }
<|
String.toList instructions

foldl 函数中,我们使用 { visited, loc, result } 因为我们不仅需要知道一个新位置,如 calculateFinalLocation,但也已经访问过位置和结果(我们是否已经找到交叉路口?)。我在这里使用了 lambda 函数,但如果您愿意,可以将其移至常规函数。

这是它的实时代码示例:https://ellie-app.com/MDbmPFsjvwa1

关于Javascript 处理日期的显示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331653/

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