gpt4 book ai didi

javascript - 为每个数组元素定义一个函数

转载 作者:行者123 更新时间:2023-11-28 19:24:28 25 4
gpt4 key购买 nike

我想在不编写X次代码的情况下完成此操作。你如何在 JavaScript 中做到这一点?我来自 java 。

        floors[0].on("up_button_pressed", function() { 
elevator.goToFloor(floors[0].floorNum());
} );
floors[0].on("down_button_pressed", function() {
elevator.goToFloor(floors[0].floorNum());
} );

floors[1].on("up_button_pressed", function() {
elevator.goToFloor(floors[1].floorNum());
} );
floors[1].on("down_button_pressed", function() {
elevator.goToFloor(floors[1].floorNum());
} );

floors[2].on("up_button_pressed", function() {
elevator.goToFloor(floors[2].floorNum());
} );
floors[2].on("down_button_pressed", function() {
elevator.goToFloor(floors[2].floorNum());
} );

floors[3].on("up_button_pressed", function() {
elevator.goToFloor(floors[3].floorNum());
} );
floors[3].on("down_button_pressed", function() {
elevator.goToFloor(floors[3].floorNum());
} );

floors[4].on("up_button_pressed", function() {
elevator.goToFloor(floors[4].floorNum());
} );
floors[4].on("down_button_pressed", function() {
elevator.goToFloor(floors[4].floorNum());
} );

最佳答案

首先,在

floors[0].on("up_button_pressed", function () { 
elevator.goToFloor(floors[0].floorNum());
});

函数内的floors[0]始终与触发事件的对象相同,因此我将其更改为使用this:

floors[0].on("up_button_pressed", function () { 
elevator.goToFloor(this.floorNum());
});

然后,只需使用 forEach 对所有楼层执行此操作即可:

floors.forEach(function (floor) {
floor.on("up_button_pressed", function () {
elevator.goToFloor(this.floorNum());
});
// same for "down_button_pressed" here
});

由于处理函数不需要访问外部变量 floor 并使用 this,如果您愿意,您甚至可以在循环外定义它们并按名称使用它们:

function onFloorUp() {
elevator.goToFloor(this.floorNum());
}
// same for onFloorUp

floors.forEach(function (floor) {
floor.on("up_button_pressed", onFloorUp);
// same for "down_button_pressed" here
});

关于javascript - 为每个数组元素定义一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com