我正在尝试在 JavaScript 中将整数字符串拆分为数组。
原来我有:
m.rows[7] = new Array (8,11);
我将其更改为:
var nearby = nearby.split(",");
m.rows[7] = new Array (nearby);
(并在关卡编辑器中用逗号分隔的适当整数设置一个变量。当我将“nearby[0]”打印到控制台时,我得到“8”。当我将“nearby[1]”打印到控制台时,我得到“8”。控制台我得到 11)
但是,我在这段代码中尝试将数组中的一个元素与另一个数组中的元素进行匹配:
for (var i = m.rows[id].length-1; i >= 0; i--) {
// If the loop finds an element ID that matches the ID of the last element in the path array, do this:
console.log('test nearby 2: ' + m.rows[id][i]);
if (m.rows[id][i] == this.path_array[this.path_array.length-1].id) {
// Loop through the one array
for (var j = all_nodes.length-1; j >= 0; j--){
// If the ID of one of one of these entities matches the id of the instance that was just clicked
if (all_nodes[j].id == id) {
// Activate that node:
all_nodes[j].active = true;
}
}
break;
}
当我实际上手动将“8,11”放入上面的数组时,上面的效果完美。但是,当我尝试使用我分成数组的“附近”时,它不会。并将其打印到上面的“测试附近2”中的控制台,当我使用“附近”时,“8,11”被打印。当我手动在该数组中输入“8,11”时,我得到“11”。
我对 JavaScript 还很陌生,所以我可能在这里遗漏了一些非常明显的东西——有人能解释一下吗?
谢谢!
最佳答案
这不是数组的工作原理。在 new Array(8, 11)
中,8
和 11
是参数。在new Array(nearby)
中,nearby
是一个参数。然而,要实现您需要的功能非常简单; nearby
已经是一个数组,所以只需分配它:
m.rows[7] = nearby;
或者,如果该类型让您烦恼:
m.rows[7] = [parseInt(nearby[0], 10), parseInt(nearby[1], 10)];
请注意,这里我使用了数组文字语法,[]
。 [a, b]
基本上等同于 new Array(a, b)
,出于各种原因,您应该尽可能使用文字语法。
关于javascript - 将整数字符串拆分为数组 - 元素无法被识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572203/