如何仅获取数组的属性(而不是值)?

huangapple go评论66阅读模式
英文:

How to get only properties (not values) of an array?

问题

为什么数组中的字符串索引不会增加'length'?的答案中,我发现数组既可以有值,也可以有属性。

例如,在以下代码中:

var array = [];
array['test1'] = 'property 1';
array['test2'] = 'property 1';
array[0] = 'value 1';
array[1] = 'value 2';

第二和第三行创建属性。

第四和第五行创建值。

我可以使用以下代码获取值:

array.forEach((value) => {
    console.log(value);
});

如何只获取属性?

英文:

From the answer of Why does a string index in an array not increase the 'length'?, I found out that arrays can have both value and properties.

For example in the following code:

var array = [];
array['test1'] = 'property 1';
array['test2'] = 'property 1';
array[0] = 'value 1';
array[1] = 'value 2';

Second and third line create property.

Fourth and fifth line create value.

I can get the values using:

array.forEach((value) => {
    console.log(value);
});

How can I get only the properties?

答案1

得分: 3

Second and third line create property.

Fourth and fifth line create value.

第二和第三行创建属性。
第四和第五行创建值。

No. All of those lines create a property and assigns a value to it.

不,所有这些行都创建一个属性并为其分配一个值。

The only difference is that some of those property names are integers.

唯一的区别是其中一些属性名称是整数。

How can I get only the properties?

如何只获取属性?

If you want to use properties that are not numbers then do not use an array.

如果要使用非数字属性,请不要使用数组

The purpose of an array is to store a set of values in an order. It does this using numeric property names. It has lots of special features specifically for handling numeric property names.

数组的目的是按顺序存储一组值。它使用数值属性名称来实现这一目的。它具有许多专门用于处理数值属性名称的特殊功能。

Use a regular object instead. You can convert it to an array you are iterate over with Object.entries, and filter out selected properties based on their name if you like.

使用普通对象。您可以将其转换为一个数组,然后使用 Object.entries 进行迭代,并根据名称筛选出所需的属性。

const object = {};
object['test1'] = 'property 1';
object['test2'] = 'property 1';
object[0] = 'value 1';
object[1] = 'value 2';

const logger = ([name, value]) => console.log(`${name} is ${value}`);

Object.entries(object).forEach(logger);

console.log("-------");

Object.entries(object).filter(([name]) => !/^\d+$/.test(name)).forEach(logger);
英文:

> Second and third line create property.
>
> Fourth and fifth line create value.

No. All of those lines create a property and assigns a value to it.

The only difference is that some of those property names are integers.

> How can I get only the properties?

If you want to use properties that are not numbers then do not use an array.

The purpose of an array is to store a set of values in an order. It does this using numeric property names. It has lots of special features specifically for handling numeric property names.

Use a regular object instead. You can convert it to an array you are iterate over with Object.entries, and filter out selected properties based on their name if you like.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const object = {};
object[&#39;test1&#39;] = &#39;property 1&#39;;
object[&#39;test2&#39;] = &#39;property 1&#39;;
object[0] = &#39;value 1&#39;;
object[1] = &#39;value 2&#39;;

const logger = ([name, value]) =&gt; console.log(`${name} is ${value}`);

Object.entries(object).forEach(logger);

console.log(&quot;-------&quot;);

Object.entries(object).filter(([name]) =&gt; !/^\d+$/.test(name)).forEach(logger);

<!-- end snippet -->

答案2

得分: 0

你可以使用它

var array = [];
array['test1'] = 'property 1';
array['test2'] = 'property 1';
array[0] = 'value 1';
array[1] = 'value 2';

Object.keys(array).forEach((key) => {
  if (isNaN(+key)) {
    console.log(array[key]);
  }
})
英文:

You can use it

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var array = [];
array[&#39;test1&#39;] = &#39;property 1&#39;;
array[&#39;test2&#39;] = &#39;property 1&#39;;
array[0] = &#39;value 1&#39;;
array[1] = &#39;value 2&#39;;

Object.keys(array).forEach((key)=&gt;{
  if(isNaN(+key)){
    console.log(array[key])
  }
})

<!-- end snippet -->

答案3

得分: 0

以下是您要翻译的内容:

function* nonNumericProperties(object) {
  for (const key in object) {
    // Own keys only.
    if (!Object.hasOwn(object, key)) {
      continue;
    }
    
    // Filter out non-negative integers.
    // Keys like '001' are valid.
    if (/^(?:[1-9]\d*|0)$/.test(key)) {
      
      // An array's size is capped at 2 ** 32 - 2,
      // which means integers greater than that
      // are not indices.
      // https://stackoverflow.com/a/6155063
      const parsedKey = Number(key);
      if (parsedKey <= 2 ** 32 - 2) {
        continue;
      }
    }
    
    yield [key, object[key]];
  }
}

请注意,代码部分已被翻译成中文。

英文:

You can use a couple of conditions to filter out those you don't need:

function* nonNumericProperties(object) {
  for (const key in object) {
    // Own keys only.
    if (!Object.hasOwn(object, key)) {
      continue;
    }
    
    // Filter out non-negative integers.
    // Keys like &#39;001&#39; are valid.
    if (/^(?:[1-9]\d*|0)$/.test(key)) {
      
      // An array&#39;s size is capped at 2 ** 32 - 2,
      // which means integers greater than that
      // are not indices.
      // https://stackoverflow.com/a/6155063
      const parsedKey = Number(key);
      if (parsedKey &lt;= 2 ** 32 - 2) {
        continue;
      }
    }
    
    yield [key, object[key]];
  }
}

Try it:

<!-- begin snippet: js hide: true -->

<!-- language: lang-js -->

console.config({ maximize: true });

function* nonNumericProperties(object) {
  for (const key in object) {
    if (
      !Object.hasOwn(object, key) ||
      (/^(?:[1-9]\d*|0)$/.test(key) &amp;&amp; +key &lt;= 2 ** 32 - 2)
    ) {
      continue;
    }
    
    yield [key, object[key]];
  }
}

const array = [0, 1, 2];
array.property = &#39;property&#39;;
array[Infinity] = Infinity;
array[1.5] = &#39;float&#39;;
array[2e-14] = &#39;float + scientific notation&#39;;
array[&#39;00234&#39;] = &#39;0-padded&#39;;
array[NaN] = NaN;
array[2 ** 32] = 2 ** 32;

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

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月25日 23:11:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定