6.3 操作数组的函数

本节介绍可适用于所有数组类型的函数。

Function: arrayp object

如果 object 是一个数组(即向量、字符串、布尔向量或字符表),该函数返回 t

(arrayp [a])
     ⇒ t
(arrayp "asdf")
     ⇒ t
(arrayp (syntax-table))    ;; A char-table.
     ⇒ t
Function: aref arr index

该函数返回数组或记录 arr 中索引为 index 的元素。第一个元素的索引为 0。

(setq primes [2 3 5 7 11 13])
     ⇒ [2 3 5 7 11 13]
(aref primes 4)
     ⇒ 11
(aref "abcdefg" 1)
     ⇒ 98           ; b’ is ASCII code 98.

另请参见 序列 章节中介绍的 elt 函数。

Function: aset array index object

该函数将数组 array 中索引为 index 的元素设置为 object,并返回 object

(setq w (vector 'foo 'bar 'baz))
     ⇒ [foo bar baz]
(aset w 0 'fu)
     ⇒ fu
w
     ⇒ [fu bar baz]

;; copy-sequence copies the string to be modified later.
(setq x (copy-sequence "asdfasfd"))
     ⇒ "asdfasfd"
(aset x 3 ?Z)
     ⇒ 90
x
     ⇒ "asdZasfd"

array 必须是可变的。See 可变性

array 是字符串,而 object 不是字符,则会抛出 wrong-type-argument 错误。如有必要,该函数会将单字节字符串转换为多字节字符串,以便插入字符。

Function: fillarray array object

该函数将数组 array 的所有元素填充为 object,即 array 的每一个元素都会被设置为 object。该函数返回 array

(setq a (copy-sequence [a b c d e f g]))
     ⇒ [a b c d e f g]
(fillarray a 0)
     ⇒ [0 0 0 0 0 0 0]
a
     ⇒ [0 0 0 0 0 0 0]
(setq s (copy-sequence "When in the course"))
     ⇒ "When in the course"
(fillarray s ?-)
     ⇒ "------------------"

array 为字符串且 object 并非字符,则会触发 wrong-type-argument 错误。

通用序列函数 copy-sequence(复制序列)和 length(获取长度)通常也适用于已知为数组类型的对象。See 序列


emacs

Emacs

org-mode

Orgmode

Donations

打赏

Copyright

© 2025 Jasper Hsu

Creative Commons

Creative Commons

Attribute

Attribute

Noncommercial

Noncommercial

Share Alike

Share Alike