面向对象的 JavaScript 书中的问题:想象一下 Array() 不存在并且数组文字表示法也不存在。创建一个名为 MyArray() 的构造函数,其行为尽可能接近 Array()。
我认为这将是一个很好的挑战来测试我的技能。这是我想出的,但它不起作用并且非常不完整..我有点难住了:
function MyArray(){
// PRIVATE FIELDS -----------------------
var initialData = arguments;
var storage;
// PRIVATE METHODS ----------------------
function refresh(){ //this doesn't work :(
for(var i = 0; i < storage.length; i++){
this[i] = storage[i]
}
};
function initialize(){
storage = initialData;
refresh();
}
function count(){
var result = 0;
for(var item in this){
//console.log(item, parseInt(item), typeof item);
if(typeof item == 'number'){
result++;
}
}
return result;
};
initialize();
// PUBLIC FIELDS -------------------------
this.length = count();
// PUBLIC METHODS ------------------------
//todo:
this.push = function(item){
refresh();
}
this.pop = function(){}
this.join = function(){}
this.toString = function(){}
}
var c = new MyArray(32,132,11);
console.log(c, c.length);
这不适用于任何生产代码或任何项目..只是为了尝试更多地学习 JavaScript。任何人都可以尝试帮助我使用这段代码吗?
问题是你可以使用参数对象。它不是使用 Array() 创建的数组,因此您不会违反练习规则。您需要执行以下操作:
this.length = 0;
for (var i in arguments) {
this[this.length] = arguments[i];
this.length++;
}
我忘记提及 ANY 对象都是关联数组,因此在练习中应用关联数组并不是错误的事情,因为我们不使用 Array() 对象本身。
对于问题的作者:在您的示例中,您使用:这个[“i”] = 存储[i]等于this.i = 存储[i]。尝试删除引号并像这样使用它this[i] = 存储[i]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)