如何跳过数组如果在javascript中为空
问题描述:
我通过json_decode从json url创建一个数组。我做了一些与各种嵌套数组的东西。我也想用所有嵌套数组的数据做一些事情。因此,我认为将数组重新组合成一个(但现在不嵌套)并循环通过它会很方便。 concat作品完美。但是,当我尝试在键/值上对新数组进行排序时,它出错了,我知道为什么。一个或多个有时为空的数组(动态数据源)。因此该阵列是例如;如何跳过数组如果在javascript中为空
"various":null
这就是我如何为我的脚本创建各种变量。
var data_hazards = data_all['alerts'][0]['hazards'];
var data_various = data_all['alerts'][0]['various'];
var data_standstill = data_all['alerts'][0]['standstill'];
var data_roadclosed = data_all['alerts'][0]['roadclosed'];
var data_accidents = data_all['alerts'][0]['accidents'];
var data_police = data_all['alerts'][0]['police'];
var data_construction = data_all['alerts'][0]['constructions'];
var data_jams = data_all['alerts'][0]['jams'];
//Concat the above arrays
var data_total = data_hazards.concat(data_various).concat(data_standstill).concat(data_roadclosed).concat(data_accidents).concat(data_police).concat(data_construction).concat(data_jams);
现在我想知道如何跳过concat()中的数组时,它是空的。
有没有人有想法?
喜欢听到你的消息。
问候,
范尼
答
你可以使用一个默认为空数组concatination所有阵列。你不需要连锁Array.concat
,因为你可以使用更多的数组作为参数。
var data_total = [].concat(
data_hazards || [],
data_various || [],
data_standstill || [],
data_roadclosed || [],
data_accidents || [],
data_police || [],
data_construction || [],
data_jams || []
);
其他的解决方案可能是一个具有值的数组。
var data_total = [
data_hazards, data_various, data_standstill, data_roadclosed, data_accidents, data_police, data_construction, data_jams
].reduce((r, a) => r.concat(a || []), []);
测试用例为空数组或默认阵列falsy值:
// concat empty array to an empty array
console.log([].concat([])); // []
// use default array if falsy value
console.log([].concat(null || [])); // []
// concat a value to an empty array
console.log([].concat(['foo'])); // ['foo']
+0
这工作完美!谢谢!没有时间来提前实施解决方案。回复晚了非常抱歉。非常感谢您的帮助! – Ruudvddries
答
有没有在你的代码中的明显重复的模式,因此很多重复的。我建议以下,以解决这个问题,并在同一时间解决您的问题!
const data_total =
['hazards', 'various', 'standstill', ...]
.map(key => data_all['alerts'][0][key]) // retrieve data for each key
.filter(data => data != null) // ignore those that are null
.reduce((a, b) => a.concat(b), []); // concat them all together
您可以检查它是否是串联前空的,使用'if' –
怎么样'如果(someArray.length == 0 )'? – kamyl
数组是否为空(a.k.a中没有元素)还是为null? – nadavvadan