推送或临时数组的未定义变量

时间:2019-01-11 21:19:32

标签: javascript arrays

无法弄清楚如何将PROTOCOL的所有变量放入具有N个PROTOCOL的循环函数的新数组中(与序列1相同的形式)。问题是,在所有情况下,我都会得到不同的失败(请参阅代码中的注释未注释的输出),并且在循环后查看一下console.log之后,“动态”数组的所有输入都消失了。作为初学者感到沮丧。寻求帮助

let NR_i = 0;
let NR_i_end = 7;
let PROTOCOL = new Array();
let PROTOCOL_HTML = new Array();		
let PROTOCOL_CSS = new Array();		
let PROTOCOL_JS = new Array();	
let PROTOCOL_PHP = new Array();		
let PROTOCOL_MySQL = new Array();
let PROTOCOL_CindyJS = new Array();
let PROTOCOL_C_Cpp = new Array();	
let allgemein = [];

//-- Sequence 1 --//
PROTOCOL = [{name:"HTML", index:[].sort()},
	        {name:"CSS", index:[].sort()},
		{name:"JS", index:["document", "getElementById", "var",
		"message", "console", "log"].sort()},
		{name:"PHP", index:["echo"].sort()},
		{name:"MySQL", index:[].sort()},
		{name:"CindyJS", index:[].sort()},
		{name:"Python", index:[].sort()},
		{name:"C_Cpp", index:[].sort()}					
		];
while(NR_i <= NR_i_end) {
  var nameX_2 = [];
  if (PROTOCOL[NR_i].index.length != 0) 
    nameX_2 = 'PROTOCOL_' + PROTOCOL[NR_i].name;
    // OUTPUT - OK: PROTOCOL_JS and so on.
								
    //nameX_2.push(PROTOCOL[NR_i].index);
    // OUTPUT: TypeError: nameX_2.push is not a function
							
    //window[nameX_2].push(PROTOCOL[NR_i].index);
    // OUTPUT: TypeError: Cannot read property 'push' of undefined
								
    //nameX_2 = nameX_2.concat(PROTOCOL[NR_i].index);
    // OUTPUT: PROTOCOL_JSconcat,console, ...
    // Why is PROTOCOL_JS also in? that disturb the hole array

    //nameX_2 = nameX_2.concat(window[PROTOCOL[NR_i].index]);
    // OUTPUT: PROTOCOL_JSundefined

    //nameX_2 = [...nameX_2, ...window[PROTOCOL[NR_i].index]];
    // OUTPUT: TypeError: window[PROTOCOL[NR_i].index] is not iterable

    nameX_2 = [...nameX_2, ...PROTOCOL[NR_i].index];
    // OUTPUT: ["P", "R", "O", "T", "O", "C", "O", "L", 
    //          "_", "J", "S", "concat", "console", and so on
    // Again. Why is PROTOCOL_JS also in? that disturb the hole array
							
    console.log("protocolname_3: ", nameX_2);
  }
  NR_i++;
}
console.log("PROTOCOL_HTML: ",PROTOCOL_HTML);
console.log("PROTOCOL_CS: ",PROTOCOL_CSS);
console.log("PROTOCOL_JS: ",PROTOCOL_JS);
console.log("PROTOCOL_PHP: ",PROTOCOL_PHP);
console.log("PROTOCOL_MySQL: ",PROTOCOL_MySQL);
console.log("PROTOCOL_CindyJS: ",PROTOCOL_CindyJS);
console.log("PROTOCOL_C_Cpp: ",PROTOCOL_C_Cpp);
console.log("nameX_2: ",nameX_2);
// OUTPUT: all empty =/
//-- Sequence 2 --//
// Same struct as Sequence 1, just with different name inputs
//-- Sequence N --//
// Same struct as Sequence 1, just with different name inputs

3 个答案:

答案 0 :(得分:2)

我不是100%知道您要问什么,但这可能有帮助

PROTOCOL = [{name:"HTML", index:[].sort()},
	        {name:"CSS", index:[].sort()},
		{name:"JS", index:["document", "getElementById", "var",
		"message", "console", "log"].sort()},
		{name:"PHP", index:["echo"].sort()},
		{name:"MySQL", index:[].sort()},
		{name:"CindyJS", index:[].sort()},
		{name:"Python", index:[].sort()},
		{name:"C_Cpp", index:[].sort()}					
		];
   
arrays = new Array();
for (i = 0; i < n; i++) {
  arrays[i] = new Array();
  PROTOCOL.forEach(function(value){
    arrays[i].push(value);
  });
};

答案 1 :(得分:1)

初始化nameX_2时,会将其初始化为一个空数组:

var nameX_2 = [];

我假设您希望在以后尝试将其作为数组时使用它。

但是,稍后,您可以在if语句中重新分配nameX_2。您将其重新分配给包含'PROTOCOL_JS'的字符串。这在JavaScript中有效,不会引发错误,因为JS是动态类型语言。这意味着JS中的变量可以更改类型,就像在这里从ArrayString一样。

然后,当您尝试将元素.push()插入nameX_2时,它表示nameX_2.push不是函数。这是因为您试图在没有.push()方法的String上调用.push()。您可能打算在数组上调用它。同样,.concat()方法存在于String上,但是只是将它们首尾相连。

当您使用...(扩展运算符)时,字符串"PROTOCOL_JS"会拆分为其组成字符。发生这种情况是因为在JavaScript中,散布运算符将对象“散布”成其组成部分。对于字符串,这会将它们拆分为字符。对于数组,它将它们拆分为元素。

您可以通过用nameX_2 = 'PROTOCOL_' + PROTOCOL[NR_i].name;调用替换分配(.push())来解决此问题:

nameX_2.push('PROTOCOL_' + PROTOCOL[NR_i].name);

您还可以将while循环替换为for循环,该循环可处理迭代器的初始化,条件和增量操作。下面的代码片段应该可以实现您要执行的操作,并根据PROTOCOL数组的内容分配全局变量。但是,请注意这在JavaScript中是不好的做法,建议您改用对象或Map。

// Variables must be declared with `var` to access through `this[]`
// Bad practice, use an object.
var PROTOCOL_JS = [];
var PROTOCOL_PHP = [];

let PROTOCOL = [{name:"HTML", index:[].sort()},
	        {name:"CSS", index:[].sort()},
		{name:"JS", index:["document", "getElementById", "var",
		"message", "console", "log"].sort()},
		{name:"PHP", index:["echo"].sort()},
		{name:"MySQL", index:[].sort()},
		{name:"CindyJS", index:[].sort()},
		{name:"Python", index:[].sort()},
		{name:"C_Cpp", index:[].sort()}					
		];

for (let NR_i = 0; NR_i < PROTOCOL.length; NR_i++) {
  var nameX_2 = [];
  if (PROTOCOL[NR_i].index.length != 0) {
    // Find the protocol name
    let protocolName = 'PROTOCOL_' + PROTOCOL[NR_i].name;
    nameX_2.push(...PROTOCOL[NR_i].index);
    this[protocolName]= nameX_2;
    console.log("protocolname_3: ", nameX_2);
  }
}

console.log("PROTOCOL_JS", PROTOCOL_JS);
console.log("PROTOCOL_PHP", PROTOCOL_PHP);

以下是遵循良好做法的版本,更加清晰易读:

let PROTOCOL = [{name:"HTML", index:[].sort()},
	        {name:"CSS", index:[].sort()},
		{name:"JS", index:["document", "getElementById", "var",
		"message", "console", "log"].sort()},
		{name:"PHP", index:["echo"].sort()},
		{name:"MySQL", index:[].sort()},
		{name:"CindyJS", index:[].sort()},
		{name:"Python", index:[].sort()},
		{name:"C_Cpp", index:[].sort()}					
		];

// Object to hold 'indexes' of different protocols.
const protocolIndexes = {};

// `forEach` loop: much cleaner and more concise
PROTOCOL.forEach((protocol) => {
  protocolIndexes[`PROTOCOL_${protocol.name}`] = protocol.index;
});

// Retrieve a specific protocol
console.log("PROTOCOL_JS", protocolIndexes.PROTOCOL_JS);

// Print all protocols
console.log("Protocols: ", protocolIndexes);

答案 2 :(得分:0)

我这样做了,让我问是否有更好的方法来处理?我的问题还在于弄清楚我是否可以使代码更小。

let PROTOCOL = new Array();
let PROTOCOL_HTML = new Array();        
let PROTOCOL_CSS = new Array();     
let PROTOCOL_JS = new Array();  
let PROTOCOL_PHP = new Array();     
let PROTOCOL_MySQL = new Array();
let PROTOCOL_CindyJS = new Array();
let PROTOCOL_C_Cpp = new Array();   
let NR_i; 
PROTOCOL = [
  {name:"HTML", index:["div","button"].sort()},
  {name:"CSS", index:["background-color","color","border","padding","text-align",
                            "font-size","transition","text-decoration","display","hover"].sort()},
  {name:"JS", index:["document","getElementById","window","addEventListener","click","mouseover","mouseout","change","function","alert", "innerHTML", "Math","random"].sort()},
  {name:"PHP", index:[].sort()},
  {name:"MySQL", index:[].sort()},
  {name:"CindyJS", index:[].sort()},
  {name:"Python", index:[].sort()},
  {name:"C/C++", index:[].sort()}                   
];
for (NR_i = 0; NR_i < PROTOCOL.length; NR_i++) {
  if (PROTOCOL[NR_i].name == "HTML" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_HTML.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "CSS" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_CSS.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "JS" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_JS.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "PHP" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_PHP.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "MySQL" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_MySQL.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "CindyJS" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_CindyJS.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "Pyhon" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_Pyhon.push(...PROTOCOL[NR_i].index);
  }
  if (PROTOCOL[NR_i].name == "C_Cpp" && PROTOCOL[NR_i].index.length != 0) {
    PROTOCOL_C_Cpp.push(...PROTOCOL[NR_i].index);
  }
}