【问题标题】:What is the datatype for this collection and how to access it's values?这个集合的数据类型是什么以及如何访问它的值?
【发布时间】:2019-10-11 02:32:00
【问题描述】:

我收到的代码中有一个声明,用于为其编写逻辑。我已经弄清楚了我的算法,但我无法弄清楚这是什么数据类型。我基本上必须将每一行的“技能”值与“JavaScript”进行比较,如果是真的,我需要做一项任务。我无法获得技能的价值。此声明是什么数据类型,如何访问它的值?

我尝试使用表类型的行/列以及数组来访问值,但没有任何效果。要在此表中添加/删除行,

const newCandidates = [
 { name: "Kerrie", skills: ["JavaScript", "Docker", "Ruby"] },
 { name: "Mario", skills: ["Python", "AWS"] }
 ];

【问题讨论】:

标签: javascript arrays javascript-objects


【解决方案1】:

你有一个字典数组。您可以像这样访问它的项目:

const newCandidates = [{
    name: "Kerrie",
    skills: ["JavaScript", "Docker", "Ruby"]
  },
  {
    name: "Mario",
    skills: ["Python", "AWS"]
  }
];

console.log(newCandidates[0].skills[1])
console.log(newCandidates[1].name)

【讨论】:

    【解决方案2】:

    它是javascript中的数组。虽然 javascript 数组不过是对象。

    const newCandidates = [
         { name: "Kerrie", skills: ["JavaScript", "Docker", "Ruby"] },
         { name: "Mario", skills: ["Python", "AWS"] }
        ];
        console.log("DataType of newCandidates: ", typeof newCandidates); // prints object type
    
    
    // accessing skills array in newCandidates
    
    for(var i = 0; i < newCandidates.length; i++) {
    	let person = newCandidates[i];
    	console.log("personName: ", person["name"]);
    	// since skills is array, iterate through it.
    	for(var j = 0; j < person["skills"].length; j++) {
    		let currentSkill = person["skills"][j];
    		// do something with currentSkill
    		console.log("Skill-" + j + " : " + currentSkill);
    	}
    }

    【讨论】:

    • 我可以使用 var person=newCandidates[i];代替?
    • 是的,你可以使用它。
    【解决方案3】:

    您有一组 Javascript 对象(大括号中的所有内容)。在数组上执行 forEach 循环:

    newCandidates.forEach(e => console.log(e.skills))
    

    这将为您提供技能数组。可以使用额外的数组方法来测试技能是否包含“Javascript”

    newCandidates.forEach(candidate => {
      if(candidate.skills.includes("Javascript") {
        *execute your function*
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2021-09-13
      • 2020-12-15
      • 1970-01-01
      • 2019-09-24
      • 2014-11-15
      • 2012-03-03
      • 2020-11-12
      相关资源
      最近更新 更多