简体   繁体   English

Clojure [Script]中的…rest for maps相当于什么?

[英]What is the equivalent of …rest for maps in Clojure[Script]?

I can do map destruction like the following in JavaScript: 我可以像下面的JavaScript一样进行地图销毁:

const drop = (key, obj) => {
  const { [key]: _, ...rest } = obj;
  return rest;
}

drop('name', { name: 'book', chapters: 12 }); // => { chapters: 12 }

How can I do ...rest / & rest for maps in Clojure[Script]? 如何在Clojure [Script]中为地图...rest / & rest

There is no equivalent destructuring like that for maps in Clojure. 没有像Clojure中的地图那样的等效销毁。 I think effectively you're looking for dissoc if you just want to omit map entries by key: 我认为,如果您只想按键省略地图条目,那么您实际上正在寻找dissoc

(dissoc {:name "book" :chapters 12}
        :name)
=> {:chapters 12}

There is rest destructuring for other sequence types: 还有其他序列类型休息解构:

(let [[x & xs] [1 2 3]]
  (prn x)   ;; "1"
  (prn xs)) ;; "(2 3)"

where xs (the part after & ) is the rest of the value. 其中xs&后面的部分)是值的其余部分。

There are several other options for map destructuring: 地图销毁还有其他几种选择:

(def my-map {:name "book" :chapters 12 :extra "stuff"})
(let [{:keys [name chapters] :as m} my-map]
  (prn name)     ;; value of name key only
  (prn chapters) ;; value of chapters key only
  (prn m))       ;; the entire bound value
;; "book"
;; 12
;; {:name "book", :chapters 12, :extra "stuff"}

The use of :as in that destructuring example is probably the closest you'll get to the behavior you're seeing in JavaScript, except it doesn't exclude the explicitly destructured keys. 在那个解构示例中, :as的使用可能与您在JavaScript中看到的行为最接近,除非它不排除显式解构的键。

(let [{n :name} my-map]
  (prn n)) ;; the value of name key only, aliased

See this guide for more. 有关更多信息,请参见本指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM