我想深入了解我的代码,幕后发生了什么?我是关于JS Object原型的新手,我用它来操纵对象,但没有真正玩原型!
我有两个脚本(JavaScript),如下所示:
// First script //
function MyObject(dim=3){
this.table= [];// 2D array
this.initialiseTable(dim);
this.setTable = function (index,symbol){
// i want to change only one element of my table
this.table[index[0]][index[1]]=symbol;
};
}
MyObject.prototype ={
initialiseTable:function(dim){
var array = [];
for (let i=0; i<dim; i++){
array.push("0");
}
for (let i=0; i<dim; i++){
this.table.push(array);
}
}
};
console.log("First script")
var O = new MyObject(6);
console.log(O.table);
O.setTable([1,3],"Changed");
console.log(O.table);
// Second script
// First script //
function MyNewObject(dim=3){
this.table= [];// 2D array
this.initialiseTable(dim);
this.setTable = function (index,symbol){
// i want to change only one element on my table
this.table[index[0]][index[1]]=symbol;
};
}
MyNewObject.prototype ={
initialiseTable:function(dim){
// i delete the array variable and implement something hard but then
// i don't have the flexibility to set freely the table dimension
for (let i=0; i<dim; i++){
this.table.push([0,0,0,0,0]);
}
}
};
console.log(" ");
console.log("Second script");
var OO = new MyNewObject(6);
console.log(OO.table);
OO.setTable([1,3],"Changed");
console.log(OO.table);
两个代码之间的区别仅在于seTable定义。现在这是在O对象(第一个脚本)上调用setTable之后的表:
[ [ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ] ]
,这是在OO对象上调用setTable之后的表:
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 'Changed', 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
为什么我使用第一个脚本在对象表中获取每行的所有第三个元素?
答案 0 :(得分:0)
创建一个对象并将其分配给每个分配与为每个分配创建一个新对象之间的区别。这样:
var array = [];
for (let i=0; i<dim; i++){
this.table.push(array); // Assign pre-created array
}
将创建一个数组并将其分配给表中的每个值。但是:
for (let i=0; i<dim; i++){
this.table.push([]); // Create fresh array (`[]`) and assign
}
您可以通过查看数组是否是同一个对象来测试它:
table[0] === table[1] // true in the first example, false in the second
让我们测试一下:
var test1 = [];
var test2 = [];
// Lets quickly fill both
var filler = ['Precreated Array'];
while( test1.length < 3 ) test1.push( filler );
while( test2.length < 3 ) test2.push(['New array (' + test2.length + ')']);
// Now lets see if the entries are similar
test1.forEach(function(arr, i){
console.log('test1[0] === test1[' + i + '] | true? ', arr === test1[0], 'Same object!')
})
test2.forEach(function(arr, i){
// The first one will be true, because a duck is a duck.
console.log('test2[0] === test2[' + i + '] | false? ', arr === test2[0], 'Different object!')
})
答案 1 :(得分:0)
你正在给你的桌子喂六次相同的阵列。
你需要做这样的事情:
{{1}}
旧的一个例子&#34;为什么我的事件处理程序在我的所有列表中显示相同的数字&#34;问题。