我将其放在摘要中以便于查看。
代码可能更大,因此如何缩短代码的响应/上载速度呢?请帮忙!
LED0 = "";
LED1 = "";
LED2 = "";
LED3 = "";
LED4 = "";
LED5 = "";
LED6 = "";
LED7 = "";
LED8 = "";
LED9 = "";
LED10 = "";
LED11 = "";
LED12 = "";
LED13 = "";
LED14 = "";
LED15 = "";
var LED0_state = 0;
var LED1_state = 0;
var LED2_state = 0;
var LED3_state = 0;
var LED4_state = 0;
var LED5_state = 0;
var LED6_state = 0;
var LED7_state = 0;
var LED8_state = 0;
var LED9_state = 0;
var LED10_state = 0;
var LED11_state = 0;
var LED12_state = 0;
var LED13_state = 0;
var LED14_state = 0;
var LED15_state = 0;
request.open("GET", "ajax_inputs" + strLED0 + strLED1 + strLED2 + strLED3 + strLED4 + strLED5 + strLED6 + strLED7 + strLED8 + strLED9 + strLED10 + strLED11 + strLED12 + strLED13 + strLED14 + strLED15 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 2000);
strLED0 = "";
strLED1 = "";
strLED2 = "";
strLED3 = "";
strLED4 = "";
strLED5 = "";
strLED6 = "";
strLED7 = "";
strLED8 = "";
strLED9 = "";
strLED10 = "";
strLED11 = "";
strLED12 = "";
strLED13 = "";
strLED14 = "";
strLED15 = "";
function GetButImp0()
{
if (LED0_state === 1) {
LED0_state = 0;
strLED0 = "&LED0=0";
}
else {
LED0_state = 1;
strLED0 = "&LED0=1";
}
}
function GetButImp1()
{
if (LED1_state === 1) {
LED1_state = 0;
strLED1 = "&LED1=0";
}
else {
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButImp2()
{
if (LED2_state === 1) {
LED2_state = 0;
strLED2 = "&LED2=0";
}
else {
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function GetButImp3()
{
if (LED3_state === 1) {
LED3_state = 0;
strLED3 = "&LED3=0";
}
else {
LED3_state = 1;
strLED3 = "&LED3=1";
}
}
function GetButImp4()
{
if (LED4_state === 1) {
LED4_state = 0;
strLED4 = "&LED4=0";
}
else {
LED4_state = 1;
strLED4 = "&LED4=1";
}
}
function GetButImp5()
{
if (LED5_state === 1) {
LED5_state = 0;
strLED5 = "&LED5=0";
}
else {
LED5_state = 1;
strLED5 = "&LED5=1";
}
}
// ..........etc............//
感谢您的帮助!
最佳答案
您可以使用对象数组并使用循环对其进行初始化。这是一个例子:
var leds = [];
var nocache = "";
for(var i = 0; i <= 15; i++){
leds.push({
index : i,
state : false,
switch : function(){
var ret = "LED" + this.index + "=" + (this.state?"1":"0");
this.state = !this.state;
return ret;
}
});
}
function getURL(ledsIndexes){
var url = "ajax_inputs?";
ledsIndexes.forEach(function(ledIndex){
url+=leds[ledIndex].switch()+"&";
});
return url.replace(/\&$/, "") + nocache;
}
console.log(getURL([1,3,4,5]));
console.log(getURL([1,3,4,5]));
从代码看来,此应用似乎用于控制Arduino板的GPIO。
我的代码要做的只是创建一个包含15个对象的数组
leds
。这些对象的结构如下:index
指定这是哪个引脚,state
跟踪其状态(true
或false
),而switch
是返回a的函数。字符串(“ LED [N] = [STATE]”)并切换引脚的状态。