该算法应该将数组的两个元素相加,并将它们插入总和中使用的两个元素之间。我的功能是不打印任何东西
实施例输入==>输出:
[1, 2, 3, 4] ==> [ 1, 3, 2, 5, 3, 7, 4]
function growArray() {
var sequence = [];
sequence = window.prompt("Enter a number sequence", "1 2 3 4");
for (var i = 0; i < sequence.length - 1; i += 2) {
if (!((i + 1) in sequence)) {
return;
} // prevent out of bounds access
var new_value = sequence[i] + sequence[i + 1];
sequence.splice(i + 1, 0, new_value); // insert value at i + 1
}
for (var v in sequence) {
document.write(v + ", ");
}
}
<p>
<input id="f1" type="button" value="Function 1" onclick="growArray();" />Click to expand array
</p>
'if(!((i + 1)in sequence))'不会起作用,因为sequence只是一个字符串。 '.split(“”)'如果这是预期的输入。 –
确保你检查了控制台:'Uncaught TypeError:不能使用'in'运算符在1 2 3 4'中搜索'1'。 –
TypeError:无效'in'操作数序列 –