2 回答

TA貢獻1816條經(jīng)驗 獲得超6個贊
這只是一個簡單的例子, 在戈蘭.您也可以使用與固定道具一起使用的類似邏輯。該函數(shù)采用一個整數(shù)值 N 和一個字符串數(shù)組作為 props。mapsstructs
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))
}

TA貢獻1863條經(jīng)驗 獲得超2個贊
我無法回答Golang部分,但對于JavaScript,你最好從類中創(chuàng)建新的對象實例。創(chuàng)建類,然后傳入對象,您可以在新類實例中循環(huán)和實例化這些屬性。
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));
- 2 回答
- 0 關注
- 125 瀏覽
添加回答
舉報