Coffeescript isn't empty object
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
is object empty?
号
1 2 3 4 5 6 7 8 9 10 11 12 | update: (id, data) -> toUpdate = @find(id) if toUpdate isnt {} console.log"hi mom" console.log toUpdate toUpdate.setProperty(key, value) for own key, value of data return toUpdate find:(id) -> result = record for record in @storage when record.id is id return result or {} |
考虑到以下摩卡测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | describe '#update', -> it 'should return an updated record from a given id and data when the record exists', -> boogie = createData() archive = new Archive("Dog") dog = archive.create(boogie) result = archive.update(1, {name:"Chompie", age:1}) result.name.should.eql"Chompie" result.age.should.eql 1 result.emotion.should.eql dog.emotion it 'should return an updated record from a given id and data when the record does not exist', -> boogie = createData() archive = new Archive("Dog") dog = archive.create(boogie) result = archive.update(50, {name:"Chompie", age:1}) result.should.not.exist |
号
结果是
1 2 3 4 5 6 7 8 9 10 11 12 | Archive #update should return an updated record from a given id and data when the record exists: hi mom { id: 1, validationStrategies: {}, name: 'Boogie', age: 2, emotion: 'happy' } ? Archive #update should return an updated record from a given id and data when the record exists: 1ms Archive #update should return empty when the record does not exist: hi mom {} ? 1 of 13 tests failed: 1) Archive #update should return empty when the record does not exist: TypeError: Object #<Object> has no method 'setProperty' |
…令人惊讶,不是吗?
coffeeesccript的
1 | if toUpdate isnt {} |
因为
但是,如果
1 2 3 4 5 | EMPTY = {} find: -> # ... EMPTY |
号
稍后:
1 2 | if toUpdate isnt EMPTY #... |
例如,考虑这个简单的代码:
1 2 3 4 | a = { } b = { } console.log("a is b: #{a is b}") console.log("a isnt b: #{a isnt b}") |
。
这将在您的控制台中提供:
1 2 | a is b: false a isnt b: true |
但这是:
1 2 3 4 5 6 | class C EMPTY = { } find: -> EMPTY check: -> console.log("@find() == EMPTY: #{@find() == EMPTY}") (new C).check() |
。
会说:
1 | @find() == EMPTY: true |
。
演示:http://jsfiddle.net/mizzy/7jgdq/
因此,您需要另一种方法来检查
1 | if (k for own k of toUpdate).length isnt 0 |
或者您可以使用上面概述的特殊
短路
1 2 3 4 | (obj) -> for k of toUpdate return true false |
。
这假设您不需要