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

TMi*_*hel 1 javascript json coffeescript

具有Object多个属性属性

{
  ...,
  attributes:{
  [0]: "Capricorn One",
  [1]: "Total Recall",
  "name": "Jerry Goldsmith"
 }
}
Run Code Online (Sandbox Code Playgroud)

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

目前我这样做:

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

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

Jam*_*ice 6

你已经拥有的方法很好,但你可以通过删除parseInt呼叫来减少它.isNaN会为你做到这一点:

for d of data.attributes
  if !_.isNaN(d)
    # property is a number
Run Code Online (Sandbox Code Playgroud)

规范(重点添加):

如果参数强制转换为NaN,则返回true,否则返回false.

  1. 如果ToNumber(number)是NaN,则返回true.
  2. 否则,返回false.

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

for d of data.attributes
  if !isNaN(d)
    # property is a number
Run Code Online (Sandbox Code Playgroud)