为什么应用跳过用于参数的数组的第一个元素?
问题描述:
我将对象文字添加到原型。我通过获取对象的属性并将值放入数组来完成此操作。然后我使用构造函数创建一个新对象,并将数组作为参数。为什么应用跳过用于参数的数组的第一个元素?
唯一的问题是构造函数(使用apply)在创建新对象时跳过了数组中的第一个元素,因此将错误的值分配给新对象中的错误属性 - 最后一个值空。
在调试器中,数组和构造函数都以正确的顺序显示属性/元素。然而输出是不正确的。
我知道我可以通过将参数直接放入新的对象构造函数来创建新对象。但是这很难阅读。除非有另一种将物体附着到原型的方式?或者整理我的数据,为构造函数做好准备?
下面是代码:
(function(root, undefined) {
var roomArray = [
{
locationIndex: 0,
name: "North room",
description: "The room is bare, there is a smashed window on the North wall, beyond which you see a grey mist.",
exits: {north: false, south: 1, east: false, west: false, down: false, up: false}
},
{
locationIndex: 1,
name: "Room 1",
description: "It is hard to see much here.",
exits: {north: 0, south: 3, east: 2, west: false, down: false, up: false}
},
{
locationIndex: 2,
name: "Room 2",
description: "A bedroom.",
exits: {north: false, south: false, east: false, west: 1, down: false, up: false}
},
{
locationIndex: 3,
name: "kitchen",
description: "A kitchen.",
exits: {north: 1, south: false, east: false, west: false, down: false, up: false}
}
];
// Room constructor
function Room(location, name, description, exits) {
this.location = location;
this.name = name;
this.description = description;
this.exits = exits;
}
// Create Rooms
roomArray.forEach(function(room, index) {
var convertArray = [];
for (var props in room) {
convertArray.push(room[props]);
}
eval("room_" + index + " = new (Room.bind.apply(Room, convertArray))()");
console.log(convertArray);
console.log(eval("room_" + index))
});
})(this);
答
试试这个
root['room_' + index] = new (Function.prototype.bind.apply(Room, convertArray))();
或现代的JavaScript
root['room_' + index] = new Room(...convertArray)
答
Room.bind.apply(Room, convertArray)
是问题。您是bind
函数,而不是直接构造函数。由于绑定需要this
作为第一个参数,因此apply
也必须提供两次。
喜欢的东西
Function.bind.apply(Room, [null].concat(convertArray))
应该工作。
+0
啊,谢谢。现在明白这个问题,真的让我很困惑,非常感谢。 – Cuckoo
为什么你有一个参数给你的函数调用'undefined'? –
*惯,只是为了确保'未定义'实际上意味着'未定义'。这可能不是必要的,我只是以这种方式来学习。 – Cuckoo