我试图在JS中(也在Go中)创建一个函数,使N个对象具有N个属性。
我想要一个函数,返回N个具有N个属性的对象。所以我得到了这个
function objects(name, age, idioms,school) {
this.name = name;
this.age = age;
this.idioms= idioms;
this.school = school;
}我都不知道该怎么做了。
发布于 2021-07-31 19:22:53
这只是maps在golang中的一个简单例子。您还可以使用与固定道具一起使用structs的类似逻辑。函数接受一个int值N和一个字符串数组,这两个字符串数组是支持的。
package main
import (
"fmt"
)
func createDynamicMap(n int, pr []string) ([]map[string]interface{}) {
var listOfMap []map[string]interface{}
for i := 0; i < n; i++ {
dm := make(map[string]interface{})
for _, v := range pr {
if _, ok := dm[v]; !ok {
dm[v] = nil // all props initialised as nil
}
}
listOfMap = append(listOfMap, dm)
}
return listOfMap
}
func main() {
dynamicMap := createDynamicMap(10,[]string{"name","age","gender"})
fmt.Println(len(dynamicMap))
}发布于 2021-07-31 19:06:08
我不能回答Golang部分,但是对于JavaScript,您最好使用A类创建新的对象实例。创建类,然后传入属性为can环行的对象,并在新的类实例中进行实例化。
class Creator {
// args can be an object with n amount of
// properties
constructor(args) {
// Just loop over the entries and assign each value
// to the instance
Object.entries(args).forEach(([key, value]) => {
this[key] = value;
});
};
}
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));
https://stackoverflow.com/questions/68604907
复制相似问题