spop

1. 基本語法

spop(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?