如何创建一个函数来创建具有N个属性的N(个)对象?

我试图在JS中(也是在Go中)创建一个函数,以生成具有N个属性的N个对象。


我想要一个返回具有N个属性的N个对象的函数。所以我得到了这个:


function objects(name, age, idioms,school) { 

    this.name = name;

    this.age = age;

    this.idioms= idioms;

    this.school = school;

}

我甚至不知道如何在Go中做到这一点。


临摹微笑
浏览 98回答 2
2回答

潇湘沐

这只是一个简单的例子, 在戈兰.您也可以使用与固定道具一起使用的类似逻辑。该函数采用一个整数值 N 和一个字符串数组作为 props。mapsstructspackage mainimport (&nbsp; &nbsp; "fmt")func createDynamicMap(n int, pr []string) ([]map[string]interface{}) {&nbsp; &nbsp; var listOfMap []map[string]interface{}&nbsp; &nbsp; for i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; dm := make(map[string]interface{})&nbsp; &nbsp; &nbsp; &nbsp; for _, v := range pr {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if _, ok := dm[v]; !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dm[v] = nil // all props initialised as nil&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; listOfMap = append(listOfMap, dm)&nbsp; &nbsp; }&nbsp; &nbsp; return listOfMap}func main() {&nbsp; &nbsp; dynamicMap := createDynamicMap(10,[]string{"name","age","gender"})&nbsp; &nbsp; fmt.Println(len(dynamicMap))}

小唯快跑啊

我无法回答Golang部分,但对于JavaScript,你最好从类中创建新的对象实例。创建类,然后传入对象,您可以在新类实例中循环和实例化这些属性。class Creator {&nbsp;&nbsp; // args can be an object with n amount of&nbsp; // properties&nbsp; constructor(args) {&nbsp; &nbsp; // Just loop over the entries and assign each value&nbsp; &nbsp; // to the instance&nbsp; &nbsp; Object.entries(args).forEach(([key, value]) => {&nbsp; &nbsp; &nbsp; this[key] = value;&nbsp; &nbsp; });&nbsp; };}const obj = { name: 'Bob', age: 2, idioms: 'etc', school: 'Grange Hill' };const obj2 = { name: 'Steve', job: 'Farmer' };console.log(new Creator(obj));console.log(new Creator(obj2));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go