简体   繁体   English

使用 javascript 中的 for in 循环从对象中获取值

[英]get value out of an object using a for in loop in javascript

I'm a JS newbie and am struggling to understand how to get the value out of an object when using a for in loop.我是 JS 新手,正在努力理解如何在使用 for in 循环时从对象中获取值。 Could you all share your knowledge with me please.大家能不能和我分享一下你的知识。 Thanks!谢谢!

Here's my problem, the code below just logs the properties and I'm trying to use a for-in loop to find if an object contains the value "apple"这是我的问题,下面的代码只记录属性,我正在尝试使用 for-in 循环来查找对象是否包含值“apple”

var mac = {
    company: 'apple',
    product: 'iPhone',
    price: 300
};

for (var key in mac) {
  console.log(key);
}

Try this:试试这个:

for (var key in mac) {
  if (mac[key] === 'apple'){
    console.log('Contains apple');
  }
}

Solution 1解决方案1

As your question says, if all you wanted to do is to check if apple is one of the values of the object, you can use Array.some and Object.keys method like this正如您的问题所说,如果您只想检查apple是否是对象的值之一,则可以像这样使用Array.someObject.keys方法

var foundApple = Object.keys(mac).some(function(key) {
    return mac[key] === "apple";
});
console.log(foundApple);

Note: Both those functions are pretty additions to the language, so you might want to check the compatibility, before you use them.注意:这两个函数都是该语言的重要补充,因此您可能需要在使用它们之前检查兼容性。

  1. Compatibility table for Array.some
  2. Compatibility table for Object.keys

Solution 2:解决方案2:

If you are looking for a solution which is compatible with all the common browsers, you can do like this如果您正在寻找与所有常见浏览器兼容的解决方案,您可以这样做

var foundApple = false;
for (var key in mac) {
    foundApple = (mac[key] === "apple");
    if (foundApple) break;
}

It should be应该是

for (var key in mac) {
  console.log(key, mac[key]);
}

I wanted a take a moment to throw my own answer in here.我想花点时间在这里抛出我自己的答案。 I was looking this up earlier and I found an answer real quick.我早些时候正在查找这个,我很快就找到了答案。 I'll try to explain in the event anyone else has a hard time with this concept in general (ie usually newer folks).如果其他人在一般情况下(即通常是新人)对这个概念感到困难,我会尝试解释。

Overview概述

In vanilla Javascript/ECMAscript you can loop through either arrays or objects using the for loop constructor.在 vanilla Javascript/ECMAscript 中,您可以使用 for 循环构造函数遍历数组或对象。 The format of the for loop just depends on what you're looping over: Array or Object. for 循环的格式仅取决于您循环的内容:数组或对象。

Read more about for loops in general here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for在此处阅读有关一般 for 循环的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

For loops with Objects带对象的 For 循环

The syntax of a for loop is a bit different than an array and is commonly referred to as a "for in" loop. for 循环的语法与数组略有不同,通常称为“for in”循环。

You can read more about "for in" looping in Javascript here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in您可以在此处阅读有关 Javascript 中“for in”循环的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Here's the syntax:这是语法:

for( key in object) {
  console.log(key); // this logs the key name in the loop to the console
  console.log(object[key]) // this logs the key value in the loop to the console
}

Breaking down what's happening above:分解上面发生的事情:

key is just a generic variable that represents the object's keys in the loop. key只是一个通用变量,代表循环中对象的键。 This can be anything you want:这可以是你想要的任何东西:

for( someBullShit in object) {
  console.log(someBullShit); 
  console.log(object[someBullShit]);
}

This loop would have the same output as the previous example.此循环将具有与前一个示例相同的输出。

Accessing Object Values in a "for in" loop在“for in”循环中访问对象值

As stated in the above example, you can access the value of an object key in a "for in" loop exactly like you normally would, except you'll use your "key variable" in place of the actual key name.如上例所述,您可以像往常一样在“for in”循环中访问对象键的值,但您将使用“键变量”代替实际键名。

Example:例子:

object[keyname] // this represents the value of a given key

I've also included extra info below in case someone finds it useful:我还在下面提供了额外的信息,以防有人觉得它有用:

For Loops with Arrays带数组的 For 循环

The format for a "standard" for loop is simple: “标准” for 循环的格式很简单:

for ([initialization]; [condition]; [final-expression]) statement for ([initialization]; [condition]; [final-expression]) 语句

In simple terms:简单来说:

Initialization - Set a starting point (which for counting purposes in Javascript would be an index of 0.初始化- 设置一个起点(在 Javascript 中用于计数目的是索引 0。

Example:例子:

var array = [1,2,3,4,5];

for(var i = 0; [condition]; [final-expression]) {
   ...
}

This means the loop starts counting at 0这意味着循环从 0 开始计数

Condition - This sets when the loop stops.条件- 设置循环停止的时间。 99.9% of time you're going to tell your loop to end when it successfully loops through each item once. 99.9% 的时间你会告诉你的循环在它成功循环每个项目一次时结束。

Example:例子:

var array = [1,2,3,4,5];

for([initialization]; i < array.length ; [final-expression]) {
   ...
}

This means that the loop should run as long as the number of times the loop has run is less than the length of the array.这意味着只要循环运行的次数小于数组的长度,循环就应该运行。

Final Expression - Here you are telling your loop what to do after the loop finishes (ie after you successfully loop through each item in the array, do this ).最终表达式- 在这里你告诉你的循环在循环结束后要做什么(即在你成功遍历数组中的每个项目后,执行这个)。 99.9% of the time this will be an increment to the index so the index's value increases by 1 each time the loop runs (just like counting off on your hand).在 99.9% 的情况下,这将是索引的增量,因此每次循环运行时,索引的值都会增加 1(就像在您手上倒数一样)。

Example:例子:

var array = [1,2,3,4,5];

for([initialization]; [condition]; i++) {
   ...
}

The final expression value there just says increase the value of this variable by 1.那里的最终表达式值只是说将此变量的值增加 1。

   for (let [key, value] of Object.entries(object_name)) {
     console.log(key +" : " + value + "\n");
} 

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. Object.entries() 方法返回给定对象自己的可枚举字符串键控属性 [key, value] 对的数组,其顺序与 for...in 循环提供的顺序相同。 (The only important difference is that a for...in loop enumerates properties in the prototype chain as well) check mozilla developer network for more details (唯一重要的区别是 for...in 循环也枚举原型链中的属性) 查看 mozilla 开发者网络以获取更多详细信息

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

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