简体   繁体   English

Javascript json,检查所有键是否为未定义('null')并设置默认值

[英]Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. 首先,我想补充一下,我现在只学习了2天的javascript。 I'm pretty much way ahead of myself with what I'm trying to get but here goes. 我要取得的成就远远领先于我自己,但事情就这样了。

I have a json array from which I get data to replace/insert in my page. 我有一个json数组,可以从中获取要替换/插入页面的数据。 The first problem I have is that if it comes across an empty ('null') key it will just stop. 我遇到的第一个问题是,如果遇到空键(“ null”),它将停止。 Will not even try to continu. 甚至不会尝试继续。

document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;

json.img2.link is empty ('null' response from json.). json.img2.link为空(json为“ null”响应。)。 javascript will then not replace "id2" but it also won't replace "id3". 然后,javascript将不会替换“ id2”,但也不会替换“ id3”。

I'm now trying to find a solution where it will if nothing else at least set a default. 我现在正试图找到一种解决方案,该解决方案至少可以设置默认值。

The script is not continuing executing because it comes to an error --trying to access property link of an undefined object 脚本由于出现错误而无法继续执行-试图访问未定义对象的属性链接

Try 尝试

document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';

This way your are checking for undefined (ie null) object in img2 and assigning the default value. 这样,您将检查img2中的undefined (即null)对象并分配默认值。 This assumes that what is not defined (null) is the img2 object. 假设未定义(空)为img2对象。

Actually I don't think your code should work at all, you are missing the . 实际上,我认为您的代码根本不起作用,因为您缺少. before the src So, try 在之前src所以,尽量

document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;

and let us know if that doesn't solve the problem. 让我们知道这是否不能解决问题。

Btw, +points for learning JavaScript and not just straight into jQuery! 顺便说一句,+学习JavaScript的要点,而不仅仅是jQuery!

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

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