【发布时间】:2019-06-13 13:14:57
【问题描述】:
我正在尝试从 things(1-10 个对象)和 stuff(1-10 个对象)中返回所有 it(字符串) )。我注意到我无法使用通配符来做到这一点,但我想知道是否还有其他方法可以做到这一点?
我想返回一个包含所有 it 的数组。
response.things[0].stuff[0].它会从我的第一个对象返回字符串,分别是 things 和 stuff,但是
$.get("https://page.json", function(response) {
var substr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arrayIts = [];
$.each(substr , function(index, val) {
var arrayIts = response[index];
console.log(arrayIts.things[index].stuff[val].it);
});
});
Above 将返回所有 it 直到它返回 undefined 然后停止。
我如何返回所有 it 并可能忽略/跳过未定义?
到目前为止,我的解决方案如下所示。
$.getJSON('https://jsonplaceholder.typicode.com/posts', function(data) {
var arrayData = [];
try {arrayData.push("<li>"+data[0].id+"</li>");}catch(e){}
try {arrayData.push("<li>"+data[1].id+"</li>");}catch(e){}
try {arrayData.push("<li>"+data[2].id+"</li>");}catch(e){}
try {arrayData.push("<li>"+data[100].id+"</li>");}catch(e){arrayData.push("<li>skipped</li>")}
try {arrayData.push("<li>"+data[3].id+"</li>");}catch(e){}
try {arrayData.push("<li>"+data[99].id+"</li>");}catch(e){}
document.getElementById('listId').innerHTML = arrayData.join("");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="listId">empty</ul>
【问题讨论】:
-
response是什么? -
你好,Joe,也许这会有所帮助:stackoverflow.com/questions/286141/… 你为什么不只使用一个 reduce、check/descart undefined 并将所有“it”累积到一个数组中。
标签: javascript json undefined wildcard