如何为JavaScript数组创建动态密钥名称?

时间:2015-04-30 15:46:05

标签: javascript arrays coffeescript jasmine

TL; DR;

我希望这段代码

console.log Object.defineProperty(results,match, {value:[]})

输出如下内容:

[foo: Array[0]]

这适用于控制台,但不适用于Jasmine正在测试的代码。

详情

我正在尝试创建JavaScript哈希。我似乎无法在我的代码中动态创建属性,尽管我能够在JSFiddle中完成它。我首先编写测试,并且代码似乎在Jasmine下失败了。我不知道这是不是Jasmine的错。

这是我的fiddle。我正在使用Object.defineProperty第一次定义属性,但我也试过:

if typeof results[match] = 'undefined' then results[match] = []

这也不起作用。在我的Jasmine代码中,它不会创建属性。

1 个答案:

答案 0 :(得分:1)

有几个小问题(上面的评论中提到了几个),更正在代码注释中:

testsForRev = [{
    id: 1
    rev_id: 10
    is_current: true
    test_params: [
      {name: 'device_param1', value: '1/#{1PLACEHOLDER1}'}
      {name: 'device_param2', value: 'TEST/#{2PLACEHOLDER2}/#{3PLACEHOLDER3}'}
      {name: 'test_param1', value: 'NOT_A_PLACEHOLDER'}
    ]
  },{
    id: 2
    rev_id: 10
    test_params: [
      {name: 'device_param3', value: '1/#{4PLACEHOLDER4}'}
      {name: 'device_param4', value: 'TEST/#{5PLACEHOLDER5}/#{6PLACEHOLDER6}'}
      {name: 'test_param2', value: 'NOT_A_PLACEHOLDER'}
      {name: 'device_param7', value: '5/#{4PLACEHOLDER4}'}
    ]
  }]

parseDeviceParams= (test,results) ->
    for param in test.test_params
        param.value.replace /#{(.*?)}/g, (str,match,start, usage) ->

            #conditionally create array for the property. Alternative
            #would be 'results[match] and results[match].push...'
            #which would conditionally activate but not create the
            #empty array if not already present...
            results[match] ?= []
            results[match].push {name: param.name, usage: usage}

            #i've added a return value for the substr, but you were
            #calling just for side effects?
            return match

    return results

aggregate = {} #changed to object, now need to define custom toString

Object.defineProperty aggregate, 'toString',
    value: ->
        str = ''
        for index, value of this
            str += "#{index}: "
            for item in value
                for key, val of item
                    str += "\t#{key}: #{val}\n"

        return str

for test in testsForRev
    parseDeviceParams test, aggregate
console.log "results:\n#{aggregate.toString()}"

fiddle