打字稿问题遍历元组数组并获取特定值

时间:2021-01-16 11:42:32

标签: typescript

我必须编写一个接受元组数组的函数,每个元组由一个名字和一个年龄组成。该函数应仅返回名称。

所以我是这样写的:

type someTuple = [string, number]

function names(namesAndAges: someTuple[]) {
  let allNames: string[]
  allNames.push(namesAndAges.forEach( nameAndAge => nameAndAge[0]))
  
  return allNames
}

当我用这个调用它时:

names([['Amir', 34], ['Betty', 17]]);

我收到此错误:

type error: type error: Variable 'allNames' is used before being assigned.

谁能指出这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

您没有将 let script = document.createElement("script"); script.src = "https://code.jquery.com/jquery-3.4.1.min.js"; script.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(script); function goto(name_of_page) { // go get the page and paste it on the current page var request = new XMLHttpRequest(); request.open("GET", name_of_page, true); request.onload = function() { if (request.status >= 200 && request.status < 400) { let resp = request.responseText; let link = name_of_page.split("."); let name = link[0]; $("body").load(`${name_of_page}`); if ( location.href.includes("localhost") || location.href.includes("www") ) { window.history.pushState(name_of_page, "Title", name); console.log("has www or localhost"); } else { window.history.pushState(name_of_page, "Title", name_of_page); console.log("does not have www"); } } }; request.send(); } 声明为数组,因此将其更改为:

allNames

如果你想得到一个数组中的所有名字,你的函数应该是这样的:

let allNames: string[] = []

Playground