Lodash的uniqueId()方法用于生成一個(gè)全局唯一的字符串。該方法沒(méi)有任何參數(shù)。可以通過(guò)以下步驟來(lái)使用uniqueId()方法:
npm install lodash
const _ = require('lodash');
const id1 = _.uniqueId();
const id2 = _.uniqueId();
console.log(id1); // 輸出類似于 '1'
console.log(id2); // 輸出類似于 '2'
uniqueId()方法每次調(diào)用都會(huì)生成一個(gè)不同的字符串,字符串的格式通常是一個(gè)數(shù)字,從1開(kāi)始遞增。
注意:uniqueId()方法生成的字符串只在當(dāng)前運(yùn)行時(shí)環(huán)境中唯一,如果重新啟動(dòng)程序,生成的字符串可能會(huì)重復(fù)。如果需要在持久化存儲(chǔ)中保持唯一性,可以使用其他方式,例如使用數(shù)據(jù)庫(kù)自動(dòng)生成唯一的標(biāo)識(shí)符。