我可以找到一个第一级属性,但它不会让我访问颜色下的'tint'属性。通常情况下,您只需使用点到您想要达到的水平,但它对我不起作用。
obj = new Object();
obj.color.tint = "brick red";
alert(obj.color);
var arr = [];
arr[0] = obj;
alert(arr[0].color.tint);
答案 0 :(得分:2)
obj.color.tint = "brick red";
此部分将失败,因为color
不存在。 JavaScript没有"自动填充"缺口。在为color
分配tint
之前,您必须先将var obj = {};
obj.color = {};
obj.color.tint = 'brick red';
定义为对象。
var obj = {
color: {
tint: 'brick red'
}
};
此外,这可以简化为:
$(document).ready(function() {
var elements = $(".jk-content-module__image");
elements.each(function(i, obj) {
if ($(obj).find("div[style*='display: none'] img").attr("src").indexOf("blank_0.png") > 0) {
$(obj).find(".hiddenDiv").remove();
}
});
});
答案 1 :(得分:0)
obj = new Object();
obj.color = new Object(); // Try add this line
obj.color.tint = "brick red";
alert(obj.color);
var arr = [];
arr[0] = obj;
alert(arr[0].color.tint);
我不确定声明“您只需将点数用于您希望达到的任何级别”
基本上Javascript都是关于对象的,您可以使用点表示法来访问现有对象。
您可以访问obj.color
,因为您首先将obj
初始化为对象。
类似地,如果您想在obj.color
下设置属性,则必须先将obj.color
初始化为新对象,然后根据需要访问obj.color.*
答案 2 :(得分:0)
您无法将点符号链接起来创建嵌套元素,因为在您尝试访问它的属性时color
未定义;
这样做的方法:
var obj = new Object();
obj.color = {};
obj.color.tint = 'tint';
或者:
var obj = new Object();
obj.color = {tint:'tint'};
答案 3 :(得分:0)
您无法将属性分配给不存在的对象。首先,您必须创建该对象。然而,有时这是必要的。假设您想要动态地拥有该数组对象结构。我已经开发了一个Object方法来实现Object.prototype.setNestedValue()
,就像这样工作
Object.prototype.setNestedValue = function(...a) {
a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
return this;
};
var arr = [].setNestedValue(0,"color","tint","brick red");
console.log(JSON.stringify(arr));