You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS报错‘Cannot set property of undefined’,vm.dtr1初始化及赋值问题求助

Fixing the 'cannot set property of undefined' Error in Your Code

Hey there! Let's walk through why you're hitting that error and how to fix it step by step.

What's Causing the Error?

Looking at your code snippet:

vm.dtr1 = {}; 
vm.dtr1.date1 = {}; 
for(var x=0; x<5; x++){ 
  vm.dtr1[x].date1 = new Date(days[x]); // Throws "cannot set property of undefined"
}

The core issue is how you initialized vm.dtr1. You set it as a plain JavaScript object, and added a date1 property to it—but in your loop, you're trying to access vm.dtr1[x] where x is 0 through 4.

Plain objects don't automatically have numeric keys like 0-4 unless you explicitly create them. Right now, vm.dtr1[x] returns undefined for every value of x in that loop, and you can't set a property (date1) on an undefined value—that's exactly why you're seeing the error.

How to Fix It

There are two straightforward solutions depending on what you're trying to build:

1. If vm.dtr1 should be an array (since you're using numeric indices)

Change the initial initialization of vm.dtr1 to an array, then create an empty object for each index before assigning the date1 property:

vm.dtr1 = []; // Initialize as an array instead of a plain object
// If you still need a top-level `date1` property, you can add it directly to the array
vm.dtr1.date1 = {};

for(var x=0; x<5; x++){ 
  vm.dtr1[x] = {}; // First create an empty object at this index
  vm.dtr1[x].date1 = new Date(days[x]); 
}

2. If vm.dtr1 needs to stay an object (with a separate list of items)

If you want to keep vm.dtr1 as an object with its existing date1 property, add an array property (like items) to hold your loop-generated date objects:

vm.dtr1 = {}; 
vm.dtr1.date1 = {}; 
vm.dtr1.items = []; // Add an array to store your indexed items

for(var x=0; x<5; x++){ 
  vm.dtr1.items[x] = {}; 
  vm.dtr1.items[x].date1 = new Date(days[x]); 
}

Quick Recap

You were trying to access numeric keys on an object that didn't have those keys defined. By either switching vm.dtr1 to an array or adding an array property to it, you ensure each x index points to a valid object before setting its date1 property.

内容的提问来源于stack exchange,提问作者code.cycling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:42:44