js索引实现
JavaScript 索引实现方法
数组索引
数组通过数字索引访问元素,索引从0开始。例如:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[1]); // 输出: banana
对象属性索引
对象使用字符串键作为索引访问属性:
const person = {
name: 'John',
age: 30
};
console.log(person['name']); // 输出: John
Map数据结构
Map允许任何类型的键(包括对象)作为索引:
const map = new Map();
map.set('key1', 'value1');
console.log(map.get('key1')); // 输出: value1
字符串索引
字符串可以通过索引访问单个字符:
const str = 'hello';
console.log(str[1]); // 输出: e
自定义索引实现
通过对象或Map实现自定义索引系统:
class CustomIndex {
constructor() {
this.data = {};
}
set(key, value) {
this.data[key] = value;
}
get(key) {
return this.data[key];
}
}
索引性能优化
使用对象作为索引时需注意:
- 对象键会被自动转换为字符串
- 大量数据时考虑使用Map提高性能
- 避免使用复杂对象作为键
稀疏数组处理
JavaScript数组可以是稀疏的:
const sparseArray = [];
sparseArray[100] = 'item';
console.log(sparseArray.length); // 输出: 101
索引安全访问
可选链操作符防止访问不存在的索引:

const obj = {};
console.log(obj?.nested?.property); // 安全访问






