You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在数组指定索引添加对象并解决‘Unexpected identifier’错误

Fixing the "Unexpected identifier" Error & Building Your Target Array Structure

Got it, let's break down what's going wrong and how to build the array structure you want.

Why the "Unexpected identifier" Error Happens

That error pops up because you tried using a key: value syntax (like test44: { ... }) directly inside an array literal. Arrays in JavaScript are ordered collections of values—not key-value pairs (that's what objects are for). When you write test44: { ... } inside [], JavaScript doesn't recognize it as valid array syntax, hence the identifier error.

Two Correct Ways to Build Your Array

Here are two straightforward approaches to create an array with an object at index 0, plus another object at a specific index (like 44):

1. Direct Index Assignment (Simplest & Most Common)

Just initialize an empty array, then assign objects to the exact indices you want. This works even if the indices are non-consecutive (JavaScript will fill the gaps with empty slots, which are harmless for most use cases):

// Start with an empty array
const myArray = [];

// Add object to index 0
myArray[0] = {
  name: "test0",
  data: "sample data for index 0"
};

// Add object to index 44
myArray[44] = {
  name: "test44",
  data: "sample data for index 44"
};

2. Pre-Fill to Avoid Sparse Arrays (Optional)

If you don't want empty slots between your indices, pre-fill the array with a placeholder (like undefined) first, then replace the target indices:

// Create an array of length 45 (indices 0-44) filled with undefined
const myArray = Array(45).fill(undefined);

// Replace index 0 with your object
myArray[0] = { name: "test0", data: "index 0 content" };

// Replace index 44 with your object
myArray[44] = { name: "test44", data: "index 44 content" };

Quick Note

If your target index is stored in a variable (e.g., const targetIndex = 44), you can still use the same syntax: myArray[targetIndex] = { ... }—it works for static and dynamic indices alike.

内容的提问来源于stack exchange,提问作者user1234

火山引擎 最新活动