Javascript 如果对象中的数组为null,如何将其内容设置为false?
我使用以下方法获取一些数据并将其加载到对象中:Javascript 如果对象中的数组为null,如何将其内容设置为false?,javascript,Javascript,我使用以下方法获取一些数据并将其加载到对象中: test.qs = data; 然后,对象qs看起来像这样: [ {"answer":null, "answered":true, // many more fields here "answers":{"correct":null,"response":null}}, {"answer":null, "answered":true, // many more fields here "answers":{"corr
test.qs = data;
然后,对象qs看起来像这样:
[
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}},
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}}
]
如何使数组中的响应值为null,然后将其更改为false?尝试以下操作:
$(test.qs).each(function () {
$(this).each(function (i) {
for(var props in this) {
if(test.qs[i][props] == null)
test.qs[i][props] = false;
}
});
});
注意:
您需要jQuery来执行此代码+,这取决于您在哪里传递代码,它应该是全局可用的,因此如果代码不起作用,请在声明变量的地方添加下一个代码:
window.test = test;
按照我的理解,这将把所有空值都更改为false:如果“response”的值为“null”,则需要将“response”的值更改为false。假设数组中的每个对象都具有相同的结构,则此操作应可行:
for(var i = 0; i < test.qs.length; ++i)
{
if(test.qs[i]["answers"]["response"] == null)
{
test.qs[i]["answers"]["response"] = false;
}
}
for(变量i=0;i
为什么要将null
更改为false
?他们传达的信息不同。我闻到麻烦。。。如果您真的想要false
,我宁愿修复生成数据的代码。它填充一个复选框,如果尚未单击该复选框,则该复选框的值为false。
for(var i = 0; i < test.qs.length; ++i)
{
if(test.qs[i]["answers"]["response"] == null)
{
test.qs[i]["answers"]["response"] = false;
}
}