繁体   English   中英

返回包含对象信息的对象数组,从数组中选择

[英]Return an array of objects containing the Object' information, selected from Arrays

            /**
          * A prototype to create Animal objects
          */
        function Animal (name, type, breed) {
            this.name = name;
             this.type = type;
             this.breed = breed;
        }

         function createAnimalObjects(names, types, breeds) {
            // IMPLEMENT THIS FUNCTION!
            }
    /* Input should be like this

    a_name = ['Dog','Cat', 'Fowl','Goat'];
    a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat'];
    a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat'];
    createAnimalObjects(a_name,a_type,a_breed);
    */
    /* *
    [Animal{name:'Dog', type:'Security Dog' ,breed:'German Shepherd'},
Animal{name:'Cat', type:'Blue Eyes', breed:'Noiseless'}
......etc]

使用上述原型,数组应返回新的动物对象。 为了清楚起见,请帮助注释您的代码。 我是学习者。

这是一个简单的地图操作

 function Animal (name, type, breed) { this.name = name; this.type = type; this.breed = breed; } function createAnimalObjects(names, types, breeds) { if ([...arguments].some(({length}) => length !== names.length)) throw new Error('length doesnt match'); return names.map((e, i) => new Animal(e, types[i], breeds[i])); } a_name = ['Dog','Cat', 'Fowl','Goat']; a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat']; a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat']; console.log(createAnimalObjects(a_name, a_type, a_breed));

当您想要组合多个数组时,通常由 zip 函数完成:

 const zip = (...arrays) => [ ...new Array( Math.max(...arrays.map((array) => array.length)), ).keys(), ].map((index) => arrays.reduce( (result, array) => result.concat(array[index]), [], ), ); console.log(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]));

现在您可以使用 zip 组合数组,然后映射到一个 Animal 值数组

 const zip = (...arrays) => [ ...new Array(//.keys returns iterator, spread this to new array Math.max(...arrays.map((array) => array.length)),//longest array ).keys(), ].map((index) => arrays.reduce( (result, array) => result.concat(array[index]), [], ), ); const a_name = ['Dog', 'Cat', 'Fowl', 'Goat']; const a_type = ['Security Dog','Blue Eyes','Cock','she Goat']; const a_breed = ['German Shepherd','Noiseless','African Cock','American Goat']; function Animal(name, type, breed) { this.name = name; this.type = type; this.breed = breed; } console.log( //zip returns [[names[0],types[0],breeds[0]],[names[1],types[1],breeds[1],...] zip(a_name, a_type, a_breed) .map( ([name, type, breed]) =>//destructure [name,type,breed] new Animal(name, type, breed), ), );

一些文档: destructure syntaxspreadArray.prototype.mapArray.prototype.reduce

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM