如何避免在 Json 对象中"null"值,当循环时



我正在学习vainilla JS(如果我没有正确使用某些概念,请提前道歉(,在学习期间,我正在练习DOM操作和API获取,并提供了免费的API。

我有一个结构类似于下面的JSON,其中有时一些字段会获得值null,甚至更改属性的结构(正如您在第三个元素的"图像库"中看到的那样。

我正在循环使用它来做不同的事情,比如创建一个表,构建一些卡片,以及创建一个img库,在单击按钮时显示该元素的图像。但是每当循环找到";空";值,它停止,并给我一个Cannot read property 'length' of null

对象类似于此:

myObject = [
{
"field one": "something ",
"Image Gallery": [
{
"src": "anImage.jpg",
"title": "more text"
},
{
"src": null,
"title": "a title here"
},
{
"src": "otherImg.jpg",
"title": null
}      
],
"Management": null,
"Scientific Name": "Urophycis tenuis",
"Species Illustration Photo": {
"src": null,
},
"last_update": "05/19/2021 - 13:04"
},
{
"Habitat Impacts": "something ",
"Image Gallery": null,
"Management": 'some value',
"Scientific Name": null,
"Species Illustration Photo": {
"src": 'img.jpg',
},
"last_update": "05/19/2021 - 13:04"
},
{
"Habitat Impacts": "something ",
"Image Gallery":  // Note that the Image gallery structure is an array here
{
"src": "anImage.jpg",
"alt": "some text",
"title": "more text"
},     
,
"Management": 'some value',
"Scientific Name": "Urophycis tenuis",
"Species Illustration Photo": {
"src": 'img.jpg',
},
"last_update": "05/19/2021 - 13:04"
}]

我得到错误的Javascript代码是:

function createCards(myObject) {
let cardContainer = document.getElementById('cardContainer');

for (let i = 0; i < myObject.length; i++) {

aInfoButtonLeft.onclick = function () {

for (let x = 0; x < myObject[i]["Image Gallery"].length; x++) {   
console.log(myObject[i]['Image Gallery'][x]["src"])
}
}
}
}

我怎样才能防止不同的";空";值来中断迭代,还是跳过它们并跟随下一个值?我能想到的唯一方法是写if条件,但我需要每种可能包含Null 的属性都有一个

虽然大多数带循环的语言都有break语句,但其中一组语言也有continue语句,包括JavaScript。这使您可以轻松地";跳过";当前迭代:

for (let i = 1; i <= 4; i++) {
console.log('A' + i);
if (i%2 == 0) continue; // Only if a multiple of 2
console.log('  B' + i);
}
> A1
>   B1
> A2
// no B2
> A3
>   B3
> A4
// no B4

对于第一个问题,即处理null值,您可以简单地检查并继续。对于第二个问题,"Image Gallery"有时具有不同的结构,有几个选项:

  1. 以不同方式处理单个对象和对象数组
  2. 将单个对象转换为对象数组(仅使用一个对象(

我还假设您的代码注释";注意,图像库结构在这里是字符串";意思是说它是一个数组

同时展示两种解决方案,以及解决您的第一个问题,我们得到了这样的结果:

function createCards(myObject) {
let cardContainer = document.getElementById('cardContainer');
for (let i = 0; i < myObject.length; i++) {
let imgGallery = myObject[i]["Image Gallery"];
// For the first problem, ignore null values
if (imgGallery == null) continue;
/* - - - Example of 1st solution to 2nd problem (begin) - - - */
// Check whether imgGallery is an array (presumably of image objects)
if (Array.isArray(imgGallery)) {
// imgGallery is an array of images, iterate over it
for (const img of imgGallery) {
// handle img as an image
}
} else {
// imgGallery is already an image object
// handle imgGallery as an image
}
// The function would end here
/* - - - Example of 1st solution to 2nd problem (end) - - - - */
// 2nd solution for 2nd problem, we could force it to be an array
if (!Array.isArray(imgGallery))
imgGallery = [imgGallery];
// so we can just use the original code, except we now use
// the imgGallery variable of which we know it's an array
aInfoButtonLeft.onclick = function () {
for (let x = 0; x < imgGallery.length; x++) {
// I noticed the .src can still be null, which we want to skip?
// Mind that `continue`, just like `break`, works on the "closest" loop
if (imgGallery[x].src == null) continue;
console.log(imgGallery[x].src)
}
}
}

}

我注意到图像对象本身仍然可以有一个src,即null。添加另一个简单的(if src == null) continue;检查就是您所需要的,如上面更新的代码所示。

  • 尝试使用if语句。它将捕获nullundefined对象:

    if (myObject[i]["Image Gallery"] != null) {
    for (let x = 0; x < myObject[i]["Image Gallery"].length; x++) {   
    console.log(myObject[i]['Image Gallery'][x]["src"])
    }
    }
    

正如上面的海报所提到的,您需要检查该值是否为null。你根本无法循环通过一个不存在的对象!所以你的选择是在你的结构中不使用null对象——我不太确定你为什么首先需要它们,也许你可以有一个循环通过的结构和另一个占位符结构——或者检查null。

Onclick函数应该在两个for循环之外。

p.s:使用这个片段会让事情变得更容易。

var myObject = [{
"field one": "something ",
"Image Gallery": [{
"src": "anImage.jpg",
"title": "more text"
},
{
"src": null,
"title": "a title here"
},
{
"src": "otherImg.jpg",
"title": null
}
],
"Management": null,
"Scientific Name": "Urophycis tenuis",
"Species Illustration Photo": {
"src": null,
},
"last_update": "05/19/2021 - 13:04"
},
{
"Habitat Impacts": "something ",
"Image Gallery": null,
"Management": 'some value',
"Scientific Name": null,
"Species Illustration Photo": {
"src": 'img.jpg',
},
"last_update": "05/19/2021 - 13:04"
},
{
"Habitat Impacts": "something ",
"Image Gallery": // Note that the Image gallery structure is a string here
{
"src": "anImage.jpg",
"alt": "some text",
"title": "more text"
},
"Management": 'some value',
"Scientific Name": "Urophycis tenuis",
"Species Illustration Photo": {
"src": 'img.jpg',
},
"last_update": "05/19/2021 - 13:04"
}
]
function createCards(myObject) {
let cardContainer = document.getElementById('cardContainer');
aInfoButtonLeft.onclick = function() {

for (let i = 0; i < myObject.length; i++) {
if (myObject[i]["Image Gallery"]) {
for (let x = 0; x < myObject[i]["Image Gallery"].length; x++) {
console.log(myObject[i]['Image Gallery'][x]["src"])
}
}
}
}
}
createCards(myObject)
<input id="aInfoButtonLeft" type="button" value="Button">

最新更新