简体   繁体   English

遍历并使用相同的代码访问数组和对象元素

[英]Iterate through and access both array and object elements with the same code

Let's say I have a function that receives either an object or an array. 假设我有一个接收对象或数组的函数。 I would like to iterate through each element, and do something to each element as I go. 我想遍历每个元素,并在进行时对每个元素做一些事情。 I know that I can iterate through an array with forEach() or a normal for loop. 我知道我可以使用forEach()或普通的for循环遍历数组。 I can also iterate through an object and array with a for in loop . 我也可以使用for in loop遍历对象和数组。 But unlike the array case I have to check the object's elements with hasOwnProperty() . 但是与数组情况不同,我必须使用hasOwnProperty()检查对象的元素。

Can I just apply some general piece of code to both arrays and objects? 我可以只将一些通用代码应用于数组和对象吗?

Update. 更新。 This is my attempt for some object/array called value, but no console messages appear for the object case: 这是我对某些称为值的对象/数组的尝试,但对于该对象情况,没有控制台消息出现:

keysArray = Object.keys(value);
for(let key in keysArray) {
    console.log(value[key])
}

You could use 你可以用

function* entries(o) {
    if (Array.isArray(o))
        for (let i=0; i<o.length; i++)
            yield [i, o[i]];
    else
        for (const p in o)
            yield [p, o[i]];
}
// or using builtin iterators:
function entries(o) {
    return Array.isArray(o) ? o.entries() : Object.entries(o).values();
}

and call it as 并称其为

for (const [key, value] of entries(something)) {
    console.log(key, value);
}

Of course you can do a similar thing to get just the keys or just the values. 当然,您可以做类似的事情来获取键或值。

// whatever can be object or array

function doSth(whatever) {
  let myLoopable = whatever;

  // obj to array
  if (!Array.isArray(whatever)) {
    myLoopable = Object
      .keys(whatever) // get array of keys
      .reduce((acc, curKey) => [...acc, whatever[curKey]], []); // get array of values
  }

  myLoopable.forEach(value => console.log(value));
}

This is an example, not the best, you must do your own to check if it is object or not to make sure your function not failed 这是一个例子,不是最好的,您必须自己检查它是否是对象,以确保您的功能不会失败

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

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