gpt4 book ai didi

javascript - 如何获取创建的特定对象的连接值

转载 作者:行者123 更新时间:2023-12-03 08:19:14 25 4
gpt4 key购买 nike

我有两个变量

var peopleTree = {
"sandeep": "shashi",
"nanha": "shashi",
"harish": "nanha",
"divya": "harish",
"arjun": "sandeep",
"shashi": "vinoj",
"vishal": "divya"
}

var ages = {
'sandeep': 23,
'shashi': 26,
'nanha': 22,
'harish': 24,
'divya': 30,
'arjun': 25,
'vinoj': 26,
'vishal': 5
}

当使用类 person 创建一个新对象时,它必须将祖先和年龄属性添加到object(示例:当创建 var sandeep = new Person('sandeep', peopleTree,ages) 对象时,sandeep.ancestors 应该给出['sandeep', 'shashi', 'vinoj']sandeep.ages 应该给出 [23, 26, 26])

最佳答案

参见this JSFiddle。

JavaScript

var peopleTree = {
"sandeep": "shashi",
"nanha": "shashi",
"harish": "nanha",
"divya": "harish",
"arjun": "sandeep",
"shashi": "vinoj",
"vishal": "divya"
}

var ages = {
'sandeep': 23,
'shashi': 26,
'nanha': 22,
'harish': 24,
'divya': 30,
'arjun': 25,
'vinoj': 26,
'vishal': 5
}

function getAncestors(name, peopleTree, ancestors){
if(!ancestors){
ancestors = [];
}

ancestors.push(name);

if(peopleTree[name]){
return getAncestors(peopleTree[name], peopleTree, ancestors);
}

return ancestors;
}

function getAges(ancestors, agesList){
var ages = [];
for(var i = 0; i < ancestors.length; i++){
var age = agesList[ancestors[i]];
if(age){
ages.push(age);
}
}
return ages;
}

function Person(name, peopleTree, ages){
this.name = name;
this.ancestors = getAncestors(name, peopleTree);
this.ages = getAges(this.ancestors, ages);
}

var sandeep = new Person('sandeep', peopleTree, ages);

关于javascript - 如何获取创建的特定对象的连接值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33803957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com