[英]Adding properties to an object using function and bracket notation
I have an assignment on a basic javascript class that I'm taking and I can't seem to get this to work. 我正在对一个基本的javascript类进行分配,但似乎无法正常工作。 I have this unit test that was given to me: 我有这个单元测试:
describe('AddSixthProperty', function() {
it('should add a food property with the value of bbq using bracket notation', function() {
expect(objects.addSixthProperty()['food']).to.equal('BBQ');
});
});
I was given an empty function: 我得到了一个空函数:
// don't touch this line
var mysticalAnimal = objects.mysticalAnimal();
function addSixthElement(){
return
}
So I tried this: 所以我尝试了这个:
var mysticalAnimal = objects.mysticalAnimal();
objects.addSixthProperty = function(){
mysticalAnimal['food'] = "bbq";
return mysticalAnimal["food"];
};
It doesn't work. 没用 Our test page doesn't pass that. 我们的测试页没有通过。 Any help is greatly appreciated! 任何帮助是极大的赞赏!
Thanks in advance! 提前致谢!
You're returning mysticalAnimal['food']
, and then the test tries to access ['food']
again, so it ends up accessing 'bbq'['food']
, which is undefined
. 您将返回mysticalAnimal['food']
,然后测试再次尝试访问['food']
,因此最终会访问undefined
'bbq'['food']
。 You need to just return mysticalAnimal
, as well as get all your letter cases right. 您只需要return mysticalAnimal
,并正确处理所有字母大小写。 Here's a little proof of concept: 这里有一些概念证明:
var objects = (function() { var animal = { mystical: true }; return { mysticalAnimal: function() { return animal; } }; })(); var mysticalAnimal = objects.mysticalAnimal(); objects.addSixthProperty = function(){ mysticalAnimal['food'] = "bbq"; return mysticalAnimal; }; var capturedAnimal = objects.addSixthProperty(); document.getElementById('result').innerText = capturedAnimal['food'];
<p id="result" />
Here is the function: 这是函数:
var mysticalAnimal = objects.mysticalAnimal(); objects.addSixthProperty = function(){ mysticalAnimal['food'] = "BBQ"; return mysticalAnimal; }; // Test the function console.log(objects.addSixthProperty()['food'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.