如何进行循环检查

问题描述 投票:-2回答:2

我想测试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 loops
2个回答
1
投票

这将有效,但您正在遍历整个阵列,您只需要一个匹配。我建议使用一些javascript库,如下划线(http://underscorejs.org/),它提供了很好的查找功能。

使用0到99999之间的随机数不是一个好的解决方案 - 您可能会生成重复的数字。更好的选择是一些UUID / GUID(请参见duscussion:Create GUID / UUID in JavaScript?) - 并且根本不需要在数组中搜索它,因为这是唯一的


0
投票

生成密钥的最佳方法是使用uniqid

$id = md5(uniqid(date('d/m/Y H:i'), true));
© www.soinside.com 2019 - 2024. All rights reserved.