function Title(mainTitle){
  this.mainTitle = mainTitle;
}

var projectTitle1 = new Title("Project-1 Main Title"),
projectTitle2 = new Title("Project-2 Main Title"),
projectTitle3 = new Title("Project-3 Main Title"),
projectTitle4 = new Title("Project-4 Main Title");


我喜欢访问构造函数并提取与给定索引(1-4)相关的标题。我尝试了以下方法:

  var index = 4,
  x = "projectTitle" + index,
  y = projectTitle.mainTitle;


console.log(y)返回未定义。

最佳答案

运行后,您将无法“访问构造函数”。但是,您可以做的是将每个实例放入数组中,并访问适当的索引:



function Title(mainTitle){
  this.mainTitle = mainTitle;
}
const titles = [
  new Title("Project-1 Main Title"),
  new Title("Project-2 Main Title"),
  new Title("Project-3 Main Title"),
  new Title("Project-4 Main Title"),
];
const getTitle = titleNum => titles[titleNum - 1].mainTitle;
console.log(getTitle(4));
console.log(getTitle(2));





当然,您必须按顺序向titles添加项目。如果不能依靠,则另一种可能性是将每个title放入对象中,该对象由其mainTitle中的数字索引。

09-25 17:20