TypeScript 获取 JSON 字符串中元素位置的方法
在 TypeScript 中,可以通过 'JSON.parse' 方法将 JSON 字符串解析为 JavaScript 对象,然后使用 '.indexOf' 方法或 '.findIndex' 方法来获取某个元素在数组中的位置。下面是一个示例:
const jsonString = '{"name": "Alice", "age": 30, "gender": "female"}';
const jsonObject = JSON.parse(jsonString);
// 使用 indexOf 方法获取某个元素在数组中的位置
const keys = Object.keys(jsonObject);
const index = keys.indexOf("age");
console.log(index); // 输出 1
// 使用 findIndex 方法获取某个元素在数组中的位置
const keyIndex = keys.findIndex(key => key === "age");
console.log(keyIndex); // 输出 1
在上述示例中,我们首先将 JSON 字符串解析为 JavaScript 对象,然后使用 'Object.keys' 方法获取对象的所有键,然后使用 '.indexOf' 方法和 '.findIndex' 方法来查找某个键在数组中的位置。注意,这里的位置是从零开始的索引。
原文地址: https://www.cveoy.top/t/topic/qFAV 著作权归作者所有。请勿转载和采集!