spop
1. 基本語法
spop(key
, [count:<integer>]
, callback
)
key
, [count:<integer>]
, callback
) 隨機從集合中挑選count
個成員,將該成員從集合中移除並回傳;若count
大於成員數目,則全部移除;若count
為負數,則回傳錯誤;若key
不存在,則回傳空值。
2. 範例
由於移除成員為隨機挑選,以下範例在重新執行後,結果可能會不同。
(1) 隨機移除(抽出)1個成員
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
client.smembers('food', redis.print);
client.spop('food', redis.print);
client.smembers('food', redis.print);
Reply: apple,onion,potato
Reply: onion
Reply: apple,potato
(2) 隨機移除(抽出)n個成員
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
client.smembers('food', redis.print);
let n = 2;
client.spop('food', n, redis.print);
client.smembers('food', redis.print);
Reply: apple,onion,potato
Reply: apple,potato
Reply: onion
(3) 若count
非正整數或超出範圍,則回傳錯誤
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
client.spop('food', -1, redis.print);
ReplyError: ERR value is out of range, value must between 0 and 9223372036854775807
Last updated
Was this helpful?