gpt4 book ai didi

javascript - 从 Object.freeze 获取随机对象

转载 作者:行者123 更新时间:2023-11-28 14:13:10 25 4
gpt4 key购买 nike

如何编写 getRandomCounty() 函数以始终从 countyCode 返回随机对象:

export class AppComponent {
countyCode: { [key: string]: string } = Object.freeze({
'01': 'Alba',
'02': 'Arad',
'03': 'Arges',
'04': 'Bacau',
'05': 'Bihor',
'06': 'Bistrita-Nasaud',
'07': 'Botosani',
'08': 'Brasov',
'09': 'Braila',
10: 'Buzau',
11: 'Caras-Severin',
12: 'Cluj',
13: 'Constanta',
14: 'Covasna',
15: 'Dambovita',
16: 'Dolj',
17: 'Galati',
18: 'Gorj',
19: 'Harghita',
20: 'Hunedoara',
21: 'Ialomita',
22: 'Iasi',
23: 'Ilfov',
24: 'Maramures',
25: 'Mehedinti',
26: 'Mures',
27: 'Neamt',
28: 'Olt',
29: 'Prahova',
30: 'Satu Mare',
31: 'Salaj',
32: 'Sibiu',
33: 'Suceava',
34: 'Teleorman',
35: 'Timis',
36: 'Tulcea',
37: 'Vaslui',
38: 'Valcea',
39: 'Vrancea',
40: 'Bucuresti',
41: 'Bucuresti S.1',
42: 'Bucuresti S.2',
43: 'Bucuresti S.3',
44: 'Bucuresti S.4',
45: 'Bucuresti S.5',
46: 'Bucuresti S.6',
51: 'Calarasi',
52: 'Giurgiu'
});

getRandomCounty() { // this must return random object from countyCode like {'03': 'Arges'}
// ?????
}
}

最佳答案

你可以这样做:-

function getRandomCounty(obj) {
const keys = Object.keys(obj);
const randomeIndex = Math.floor(Math.random() * (keys.length));
return obj[keys[randomeIndex]];
}

关于javascript - 从 Object.freeze 获取随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58834347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com