如何从 GitHub 获取 API 数组的所有 'items'?

How to get all the 'items' of an API array from GitHub?

我正在尝试获取存储库列表,即我的代码使用过滤器搜索存储库

Javascript 得到一个结果,其中有多个项目包含每个存储库的数据,这些存储库符合使用 URL 的过滤器:https://api.github.com/search/repositories?q=piccolowen+in:name

我可以 console.log(result.items[0].name) 获取第一个存储库的 name 值,但我想从打印到控制台的搜索中获取所有存储库。我还希望代码能够打印所有存储库及其值,无论有多少存储库适合过滤器。

这是我要添加的当前代码:

window.onload = func()
    async function func() {
        const url = 'https://api.github.com/search/repositories?q=piccolowen+in:name'
        const response = await fetch(url);
        const result = await response.json();
        const apiresult = document.getElementById('thisisanid') 
        console.log(result)
}

关于如何做到这一点有什么想法吗?

编辑: 我从这个问题中使用 while 循环找到了问题的答案:Get total number of items on Json object?

const resultLength = Object.keys(result.items).length
var arrnum = 0
while (arrnum < resultLength) {
//execute code
}

编辑 2: 我之前编辑的代码会使页面崩溃。仍在为这个巨大的错误寻找解决方案。

由于results.items return是一个对象数组,您可以使用Array.prototype.map来return所有项目名称,即:

result.items.map(item => item.name)

如果想简单的过滤掉一些属性,也可以object destructuring。假设您想要一个仅包含 nameiddescription 的项目数组,那么您可以这样做:

result.items.map(({ name, id, description }) => ({ name, id, description }))

async function func() {
  const url = 'https://api.github.com/search/repositories?q=piccolowen+in:name'
  const response = await fetch(url);
  const result = await response.json();

  // Returns an array of item names
  console.log(result.items.map(item => item.name));

  // Returns an array of object with selected keys
  console.log(result.items.map(({ name, id, description }) => ({ name, id, description })));
}

func();

数组有map function,接受回调函数。它遍历所有元素并调用回调函数并将数据推送到新创建的数组。

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

更多: Array.map

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

window.load = main();
const nameMapper = (item) => item.name;
const liMapper = (item) => `<li>${item.name}</li>`;
async function main() {
  const url = "https://api.github.com/search/repositories?q=piccolowen+in:name";
  const result = await fetch(url).then((x) => x.json());
  const names = result.items.map(nameMapper);
  const apiresult = document.getElementById("thisisanid");
  apiresult.textContent = names;

  const ul = document.getElementById("list");
  ul.innerHTML = result.items.map(liMapper).join("");
}
#list li{
  list-style: none;
  padding: 5px 10px;
  border: 1px solid black;
  max-width: 400px;
}
    <div id="thisisanid"></div>
    <ul id="list">
    </ul>

你可以点赞!

let list = document.getElementById('list');
let htmlTemplate = result.items.map(function(item) {
   return item.name
}).join("")

list.insertAdjacentHTML('beforeend', htmlTemplate)

或者你可以使用模板文字 例如 当您在 items.map()

中返回值时
return `${item.id}: ${item.name}`