我想测试local_key
是否已经存在,如果它存在生成另一个local_key
并再次检查
// Here I go throught an object and try to return a index
const local_key = messagesRow.map((message, key) => {
return message.local_key;
}).indexOf(message.local_key);
// If it returns 0 or bigger, it means that the local_key already exists
if(local_key >= 0){
message.local_key = Math.floor(Math.random() * 9999);
}
编辑我想每次重新检查,因为如果local_key
存在并且我生成另一个,这个新的local_key
也许存在
这将有效,但您正在遍历整个阵列,您只需要一个匹配。我建议使用一些javascript库,如下划线(http://underscorejs.org/),它提供了很好的查找功能。
使用0到99999之间的随机数不是一个好的解决方案 - 您可能会生成重复的数字。更好的选择是一些UUID / GUID(请参见duscussion:Create GUID / UUID in JavaScript?) - 并且根本不需要在数组中搜索它,因为这是唯一的
生成密钥的最佳方法是使用uniqid
$id = md5(uniqid(date('d/m/Y H:i'), true));