Moh*_*bor 2 dictionary get vector clojure
到目前为止我所知道的用途是向量:
(get [1 2 3 4] 2) ; => 3
Run Code Online (Sandbox Code Playgroud)
并在地图上:
(get {:a "a" :b "B" :c "c"} :c) ; => "c"
Run Code Online (Sandbox Code Playgroud)
从文档中可以看出:
clojure.core/get([map key] [map key not-found])
如果key不存在,则返回映射到key,not-found或nil的值.
除了地图和向量之外,get的常见用法是在字符串上:
(get "Cthulhu" 2) ;; => \h
Run Code Online (Sandbox Code Playgroud)
get也适用于集合和本机Java(脚本)数组.ClojureScript和JavaScript互操作中的一种可能用法:
(def js-array (-> (js/Array 10) ;Create and fill native JS array
(.fill "a")
(.map (fn [_ i] i))))
(get js-array 3) ; => 3
Run Code Online (Sandbox Code Playgroud)
作为另一个例子,get用于按集合中的项目查找:
(get #{:b :c :a} :c) ;;=> :c
Run Code Online (Sandbox Code Playgroud)
请注意,它不适用于(已排序)的集合和索引,例如:
(get (sorted-set :b :a :c) 1) ;; throws exception
Run Code Online (Sandbox Code Playgroud)
此外,地图,向量和集合充当其成员的功能,因此您通常可以避免完全使用get:
(#{:a :b :c} :b) ; => :b
({:a 1 :b 2 :c 3} :b) ; => 2
([:a :b :c] 1) ; => :b
Run Code Online (Sandbox Code Playgroud)
使用get的优点是你可以提供一个默认值:
(get {:a :b :c} :d) ; => nil
(get {:a :b :c} :d :not-found) ; => :not-found
Run Code Online (Sandbox Code Playgroud)
又见@缩略图的回答来了解如何获得引擎盖下的作品.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |