js 一个对象下面的key是随机的,怎么获取到里面的value
时间: 2024-03-21 17:43:21 浏览: 16
如果一个对象的 key 是随机的,可以使用 `Object.keys()` 函数获取对象的所有 key,然后通过遍历获取每个 key 对应的 value。以下是示例代码:
```js
const obj = {
abc: 'hello',
def: 'world',
ghi: 'foo',
jkl: 'bar'
}
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const value = obj[key]
console.log(`${key}: ${value}`)
}
```
执行上述代码,会输出对象的每个 key 对应的 value。例如:
```
abc: hello
def: world
ghi: foo
jkl: bar
```
如果需要获取随机的 key 对应的 value,可以使用 `Math.random()` 函数生成一个随机数,乘以 key 的长度,取整数部分,得到一个随机的 key 的下标,然后通过该随机的 key 获取对应的 value。以下是示例代码:
```js
const obj = {
abc: 'hello',
def: 'world',
ghi: 'foo',
jkl: 'bar'
}
const keys = Object.keys(obj)
const randomKey = keys[Math.floor(Math.random() * keys.length)]
const randomValue = obj[randomKey]
console.log(`${randomKey}: ${randomValue}`)
```
执行上述代码,会输出随机的 key 对应的 value。例如:
```
jkl: bar
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)