大佬教程收集整理的这篇文章主要介绍了按 001 到 999 的顺序生成数字而不在数据中放置相同的数字,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个生成数字系统,它创建一个从 001 到 999 的数字,以便该数字在 Json 文件中不存在,例如 Json 文件将具有这样的数据
{
"001": {
"some data here": "IDk"
}
}
当它已经存在于该 Json 文件中时它不会添加另一个 001 但为了从 001 到 999 我尝试使用 @H_110_5@math.random() 生成数字但不知道如何创建系统不会添加另一个相同的数字
@H_772_0@解决方法像这样的循环是一种可能的解决方案。
function createnumbers(){ //numbers 001 - 999. Sequential
let numbers = [],x = 0,y = 0,z = 0,i;
for( i = 0; i < 999; i++ ){
z++;
if( z > 9 ){
y++;
z = 0;
}
if( y > 9 ){
x++;
y = 0;
}
x = x.toString();
numbers.push( '<div>' + x + y + z + '</div>' );
}
return numbers;
}
document.write( createnumbers() );
body {
font-family: Arial;
color: #999;
}
div {
display: inline-block;
margin: 0.25rem;
border-radius: 0.5rem;
padding: 0.25rem;
BACkground-color: #ccc;
color: #444;
}
,
要生成从 1 到 999 的数字,simple random function 将完成任务
function getRandomInt() {
return Math.floor(Math.random() * 999);
}
const generatednumber = getRandomInt(); // 32
因为您希望数字具有 3 个固定字符并且是一个字符串,所以您可以使用 padStart 例如
const generatedString = `${generatednumber}`.padStart(3,'0'); // 032
那么你所需要的就是遍历你的 JSON 数据并检查该键是否存在
const JSON = {
"001": {
"some data here": "idk"
}
};
const allKeys = Object.keys(JSON); // ["001"]
const hasKey = allKeys.find(x => x === generatedString) !== undefined
有了所有这些信息,然后做你想要完成的事情就会容易一些
,let data = {
"001": {
"some data here": "idk"
}
}
let randUniqueKeyGenerator = (data)=>{
keys = Object.keys(data);
found = false;
let key;
if(keys.includes('100')) return "";
while(!found){
key = Math.floor(Math.random()*101).toString()
key = ('00' + key).slice(-3)
found = !(keys.includes(key))
// to make key greater than exisTing keys,uncomment next line
//if(found) found = !(keys.some(k=>parseInt(k)>parseInt(key)))
}
return key
}
console.log(randUniqueKeyGenerator(data))
其中 data 是您需要为其生成唯一键的对象。
,您可能可以使用一个简单的 while 循环并将解析的 JSON 的 Object.keys
与当前迭代索引进行比较,如果它不在键数组中,则将其包含在内。
例如:
const json = '{"001":{"some data here":"idk"},"003":{"some data here":"idk"},"005":{"some data here":"idk"}}';
const keys = Object.keys(JSON.parse(json)).map(el => parseInt(el));
const nums = [];
let i = 1;
while (i < 999) {
if (!keys.includes(i)) {
nums.push(`${i}`.padStart(3,'0'));
}
i++;
}
console.log(nums)
以上是大佬教程为你收集整理的按 001 到 999 的顺序生成数字而不在数据中放置相同的数字全部内容,希望文章能够帮你解决按 001 到 999 的顺序生成数字而不在数据中放置相同的数字所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。