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
类似。
接下来我们可以使用calculateFirstIntersection
(Set
)实现http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Set。 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