gpt4 book ai didi

javascript - 确定对象属性名称是否为数字

转载 作者:行者123 更新时间:2023-11-30 08:06:12 25 4
gpt4 key购买 nike

拥有一个具有多个属性的对象

{
...,
attributes:{
[0]: "Capricorn One",
[1]: "Total Recall",
"name": "Jerry Goldsmith"
}
}

我想确定哪些是数字键,哪些不是。

目前我正在这样做:

for d of data.attributes
prop = parseInt(d)
if !_.isNaN(prop)
# property is a number

我想知道是否有更好/更有效的方法来做同样的事情?

最佳答案

您已有的方法很好,但您可以通过删除 parseInt 调用来稍微精简它。 isNaN 将为您完成:

for d of data.attributes
if !_.isNaN(d)
# property is a number

来自 the spec (强调):

Returns true if the argument coerces to NaN, and otherwise returns false.

  1. If ToNumber(number) is NaN, return true.
  2. Otherwise, return false.

您也可以使用原生的 isNaN 而不是 Underscore 版本,因为 d 永远不会是 undefined:

for d of data.attributes
if !isNaN(d)
# property is a number

关于javascript - 确定对象属性名称是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17943659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com