基本上,我试图解决以下问题:
灯泡连接到任意数量的开关。当翻转这些开关中的任何一个时,灯泡将从开启到关闭,或从开启到关闭。无论翻转哪个开关,或开关的数量,灯泡都会改变其状态。
let on = true,off = false
我如何编写一个在JS中执行此操作的算法
我尝试设置问题并在纸上使用命题逻辑。我把它设置如下:
var lightbulb,
switch1 = false,
switch2 = false,
switch3 = false;
function press(a)
{
var a = !a
}
for(var i = 1; i < 10; i++)
{
if(i % 2 == 0)
{
}
}
press(switch1);
我不知道我要去哪里,我所拥有的就是按下功能。我的循环毫无意义,我失去了思路。在纸上试了很久。
你可以接受一个数组,因为它移交了对象的引用和切换索引。然后改变lightbulb
。
var lightbulb = false,
switches = [false, false, false];
function press(index) {
switches[index] = !switches[index]; // change state of switch
lightbulb = !lightbulb; // change state of lightbulb
console.log('lightbulb:', lightbulb); // show what happens
console.log('switches:', switches.join(', '));
}
press(1);
press(0);
press(1);
press(2);
您需要每个开关来修改灯泡的状态,因此创建一个全局变量
var state = false; //Let it be off be default for now
然后你需要一个function
来改变它的状态
function press(){
state = !state;
alert('Current state:' + state);//alert the output
}
现在可以根据需要创建尽可能多的交换机
var switch1 = {
flip: press //Keep a reference of press function into flip
};
var switch2 = {
flip: press //Keep a reference of press function into flip
};
翻转开关
alert('flipping switch 1');
switch1.flip();
alert('flipping switch 2');
switch2.flip();
这里的工作示例
var state = false; //Let it be off be default for now
function press(){
state = !state;
alert('Current state:' + state);//alert the output
}
var switch1 = {
flip: press //Keep a reference of press function into flip
};
var switch2 = {
flip: press //Keep a reference of press function into flip
};
alert('flipping switch 1');
switch1.flip();
alert('flipping switch 2');
switch2.flip();