返回名称数组

时间:2019-05-14 12:38:32

标签: javascript

我正在努力从给定的dog对象数组中返回所有者名称数组。

我知道在这种情况下需要reduce方法,但是我不太想知道如何进行

function getDogType(dogs) {

3 个答案:

答案 0 :(得分:2)

#!/usr/bin/python3
# -*- coding: utf-8 *-

from random import randrange
from math import fabs


user1Guess = input("User 1 bet :")
user2Guess = input("User 2 bet :")
user1Guess = int(user1Guess)
user2Guess = int(user2Guess)
computerGuess = randrange(1,11)
u1diff = fabs(computerGuess-user1Guess)
u2diff = fabs(computerGuess-user2Guess)

if u1diff == u2diff:
    print("Tie")
elif u1diff < u2diff:
    print("User 1 won")
else:
    print("User 2 won")

答案 1 :(得分:1)

您需要使用数组的'map'方法

dogs.map(dog => dog.owner)

答案 2 :(得分:0)

您可以创建如下功能:

let dogs = [ 
{name: 'Beatrice', breed: 'Lurcher', owner: 'Tom'}, 
{name: 'Max', breed: 'Pug', owner: 'Izzi'}, 
{name: 'Poppy', breed: 'Pug', owner: 'Anat'} ];


function getOwnerByBreed(dogs,breed) { 
  return dogs.filter(dog => dog.breed==breed).map(dog => dog.owner);
}


console.log('Pug Owners',getOwnerByBreed(dogs,'Pug'));

console.log('Lurcher Owners',getOwnerByBreed(dogs,'Lurcher'));