JavaScript中使用方括号符号的嵌套对象



我正在努力实现以下目标:

this.inputs[options.el.find('form').attr('class')] = {};
this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;

但是,我无法在没有语法错误的情况下执行上述操作!

有什么想法我可以实现这个对象结构吗?

这种语法看起来是合法的,但是这些很长的一行代码并没有给任何人带来任何好处。把它拆开一点,这样你就能找到它的缺点了。

var className = options.el.find('form').attr('class');
var selector = options.elements[x].selector;
this.inputs[className] = {};
this.inputs[className][selector] = false;

对象的索引应该始终是字符串:

var obj = {
  a: 2;
}
obj.a = 3; //a is 3 now
obj['a'] = 4;//a is 4 now

你说options.elements[x].selectorinput[name="username"],所以我猜在这一行:

this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;

你真正想做的是:

this.inputs[options.el.find('form').attr('class')]['username'] = false;

你可以这样做:

var sel = options.elements[x].selector;
console.log( 'sel is ' + sel );
this.inputs[options.el.find('form').attr('class')][sel] = false;

确保sel是一个字符串。你可以试试

var sel = options.elements[x].selector.value;

.value位检索输入元素内部的文本

最新更新