Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

Typescript problem to loop through an array of tuple and get specific values

I have to write a function that takes an array of tuples, each tuple consists of a name and an age. The function should return only the names.

So I wrote it like this:

type someTuple = [string, number]

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

When I call it with this:

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

I get this error:

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

Can anyone point what is wrong with this code?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You didn't declare allNames to be an array, so change it to this:

let allNames: string[] = []

If you want to get all name in an array your function should be like this:

type someTuple = [string, number]

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

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

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...