简体   繁体   English

如何从javascript中的数组获取名称?

[英]How to get the name from the array in javascript?

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. 我对JavaScript相当陌生,我正在尝试从数组中提取名称Sam。 The output that I'm getting is name. 我得到的输出是名称。 How do I get Sam? 我如何得到山姆? Thank you in advance. 先感谢您。 I apologize but I know this is a fairly novice question. 我很抱歉,但是我知道这是一个新手问题。

I am trying to loop by using forEach. 我试图通过使用forEach循环。

let Person = {
  name: ['Sam']
}

let handler = Object.keys(Person)

handler.forEach(function(element){
  console.log(element)
})

 let Person = { name: ['Sam'] } for (const fn of ["values", "keys", "entries"]) { console.log(`Using: Object.${fn}()`); for (const v of Object[fn](Person)) { console.log(v); } } 

代替Object.keys使用Object.values

If you know in advance that your name array is located under the key name , then access it directly 如果您事先知道名称数组位于键name ,则直接访问它

 const person = { name: ['Sam'] }; console.log(person.name); console.log(person.name[0]); 

Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for: 否则,请使用Object.values()枚举对象中的值,但您可能会获得比简单地使用names数组更多的值,并且您将不得不找出哪个值包含要查找的名称:

 const person = { name: ['Sam'], anotherProp: 'hello' }; console.log(Object.values(person)); 

Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly. 在这种情况下,使用Object.entries()并没有帮助,就好像您使用它一样,它意味着您知道名称数组位于哪个属性下,如果是这种情况,则直接访问该数组即可。

If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation. 如果使用Object.keys() ,则可以使用object[key]括号表示法或object.key点表示法来获取值。

Object.keys(obj).forEach(key => obj[key]);

 let Person = { name: ['Sam'] } Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`)); 

 let Person = { name: ['Sam',"Bob","Alice"] } let count = Person.name.length; for(let i = 0; i<count; i++){ console.log( Person.name[i]) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM