js怎么读取对象的第一项
在JavaScript中,可以使用以下方法来读取对象的第一项:
- 使用对象的属性名进行读取:
const obj = {name: 'John', age: 25};
const keys = Object.keys(obj);
const firstKey = keys[0];
console.log(firstKey); // 输出:name
const firstValue = obj[firstKey];
console.log(firstValue); // 输出:John
- 使用
for...in循环来读取第一项:
const obj = {name: 'John', age: 25};
let firstKey;
let firstValue;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
firstKey = key;
firstValue = obj[key];
break;
}
}
console.log(firstKey); // 输出:name
console.log(firstValue); // 输出:John
以上两种方法都可以读取对象的第一项
原文地址: http://www.cveoy.top/t/topic/h1kv 著作权归作者所有。请勿转载和采集!