简体   繁体   English

无法将属性设置为对象

[英]Can't set property to object

var data = {};


....

data[someprop][someotherprop] = 'bla bla'

I get 我明白了

Uncaught TypeError: Cannot read property ... of undefined and Cannot set property of... Uncaught TypeError: Cannot read property ... of undefinedCannot set property of...

Yes, the object doesn't have these properties ..yet, but I'm setting them in that line where I get the error lol. 是的,该对象没有这些属性..但是,我在那行中设置它们我得到错误大声笑。 So what's up with that? 那有什么用呢?

You are trying to assign a property to an object that doesn't exist, running that statement is equivalent to 您正在尝试将属性分配给不存在的对象,运行该语句等效于

data.someprop.someotherprop the parser won't automatically create data.someprop for you, hence the error. data.someprop.someotherprop解析器不会自动为您创建data.someprop ,因此出错。

You have to initialize someprop 你必须初始化someprop

data.someprop = {};
data['someprop']['someotherprop'] = 'gw ganteng';

You need to set the properties in diffrent steps like this: 您需要以不同的步骤设置属性,如下所示:

var data = {};


data[someprop] = {}; 
data[someprop][someotherprop] = 'bla bla';

The object data will not have a property named "someprop" before you asssign it. 在您分配对象数据之前,对象数据将没有名为“someprop”的属性。

var data = {};
data[someprop] = {someotherprop:'bla bla'};

otherwise data[someprop] will be undefined 否则data[someprop]将是未定义的

You need to create data[someprop] first: 您需要首先创建data[someprop]

var data = {};
data[someprop] = {};
data[someprop][someotherprop] = 'bla bla'

http://jsfiddle.net/infernalbadger/zXETB/ http://jsfiddle.net/infernalbadger/zXETB/

if someprop and someotherprop are variables, Richard D's answer is correct, if they are hardcoded strings, you could write your code like this: 如果somepropsomeotherprop是变量,Richard D的答案是正确的,如果它们是硬编码的字符串,你可以像这样编写代码:

var data = {someprop:{someotherprop: 'value'}};

if, however, they are values stored in variables, and you really - really want to cram everything into a single line, try something like this: 但是,如果它们是存储在变量中的值,并且你真的 - 真的想把所有东西都塞进一行,试试这样的东西:

var data = {window.someprop : {window.someotherprop: 'value'}};

where window can be replaced by any object, if the someprop value is itself a property of an object: 其中window可以被任何对象替换,如果someprop值本身是对象的属性:

var data = {someForm.name : { formElement.name : formElement.value}};

Or jQuery objects, since your tag suggest you're using jQuery: 或jQuery对象,因为你的标签建议你使用jQuery:

var data= {$('#formId').attr('name'):{$('#formSelect').attr('name'): $('#formSelect').val()}};

Note: the jQuery example is not to be recommended, as the id selector is used twice on the same element. 注意:不建议使用jQuery示例,因为id选择器在同一元素上使用了两次。 jQuery will scan the DOM-tree twice, so you're better of storing your that #formSelect element in a variable somewhere. jQuery将扫描DOM树两次,因此您最好将#formSelect元素存储在某个变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM