Javascript Koans-无法解决一个测试
我试图从Javascript Koans中解决测试问题,但仍然停留在“反射”块上。有人能解决并解释下一个区块的解决方案吗:Javascript Koans-无法解决一个测试,javascript,arrays,object,Javascript,Arrays,Object,我试图从Javascript Koans中解决测试问题,但仍然停留在“反射”块上。有人能解决并解释下一个区块的解决方案吗: test("hasOwnProperty", function() { // hasOwnProperty returns true if the parameter is a property directly on the object, // but not if it is a property accessible via the pro
test("hasOwnProperty", function() {
// hasOwnProperty returns true if the parameter is a property directly on the object,
// but not if it is a property accessible via the prototype chain.
var keys = [];
var fruits = ['apple', 'orange'];
for(propertyName in fruits) {
keys.push(propertyName);
}
ok(keys.equalTo(['__','__', '__']), 'what are the properties of the array?');
var ownKeys = [];
for(propertyName in fruits) {
if (fruits.hasOwnProperty(propertyName)) {
ownKeys.push(propertyName);
}
}
ok(ownKeys.equalTo(['__', '__']), 'what are the own properties of the array?');
});
您必须知道,JavaScript的特点是一个原型继承模型,而不是一个经典的继承模型。实际上,这意味着继承是通过所谓的原型链来完成的 当您尝试使用“for in”访问数组的属性时,它将“爬上”原型链,一直爬到arrayname.prototype,因为它继承了它 如果您想了解更多有关此功能的信息,我强烈建议您查看Ivo Wetzel,这是我最初找到答案的地方 对于其余部分,您还应该知道javascript将数组的“自己的”属性引用为十进制数,即:第一个属性是“0”,第二个属性是“1”,等等 所以,解决方案是这样的:
test("hasOwnProperty", function() {
// hasOwnProperty returns true if the parameter is a property directly on the object,
// but not if it is a property accessible via the prototype chain.
var keys = [];
var fruits = ['apple', 'orange'];
for(propertyName in fruits) {
keys.push(propertyName);
}
ok(keys.equalTo(['0', '1', 'fruits.prototype'), 'what are the properties of the array?');
var ownKeys = [];
for(propertyName in fruits) {
if (fruits.hasOwnProperty(propertyName)) {
ownKeys.push(propertyName);
}
}
ok(ownKeys.equalTo(['0', '1']), 'what are the own properties of the array?');
})) 不客气!如果你真的想提高你的JS知识,我建议你看看Crockford的“JavaScript:好的部分”。。。这本书是每个渴望成为JS忍者的人必读的书!