Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在数组中存储值_Javascript_Jquery_Html_Arrays - Fatal编程技术网

Javascript 如何在数组中存储值

Javascript 如何在数组中存储值,javascript,jquery,html,arrays,Javascript,Jquery,Html,Arrays,在下面的代码中,我得到了条形码的扫描值 var scanCode = function () { window.plugins.barcodeScanner.scan(function(result) { alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled); localStorage.setItem("myvalue1",

在下面的代码中,我得到了条形码的扫描值

var scanCode = function () {
window.plugins.barcodeScanner.scan(function(result) {
    alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
    localStorage.setItem("myvalue1", result.text);
    window.location.href = 'page5.html';
    var barcodeVal = localStorage.getItem("myvalue1");
    var test2 = localStorage.getItem("code");
    code = JSON.parse(test2);
    var k = parseInt(localStorage.getItem("counter"));
    document.getElementById(code[k]).innerHTML = barcodeVal;
    alert(code[k]);
    alert(k);
    k++;
    localStorage["counter"] = k;
    localStorage.setItem("code", JSON.stringify(code));
}, function (error) {
    alert("Scan failed: " + error);
});
myvalue1
是我从扫描中获得的值。我在另一个js文件中将数组和计数器定义为

localStorage["counter"]=0;
var code = {};
localStorage.setItem("code", JSON.stringify(code));
现在我正在尝试将id存储在数组
code[]
中,并尝试在
page5.html
中打印它。上述
也在相同的
page5.html
中定义。另外,我正在一次又一次地调用扫描功能来扫描多个条形码。我正在将html中的值打印为

<tr>
    <td>2</td>
    <td id="code[0]"></td>
</tr>

2.

由于
无法将属性“innerHTML”设置为null,我收到了错误。接下来我该怎么办?请帮帮我。提前感谢

当您在指令中执行代码[k]时,可以从JSFIDLE中看到这一点

document.getElementById(code[k]).innerHTML = barcodeVal;
代码不被理解为字符串数组,而是字符串,因此在代码[0]处点选它不会指向您的id,而是指向括号


在更新后的JSFIDLE中对您的代码执行一次修改,因为我必须保存数组中的条形码数,例如
n
。因此,如果我调用数组
var code=[]类似于此,如果在html中声明
id
,则类似于
id=“test[0]”
,同样。这样的声明正确吗?您将数组声明为
var code=[“Test”,“Test2”]
对有限的条目集有效,但如果我有大约15-20个条目,那么我该怎么办?Javascript数组接受任意数量的条目和混合类型。将其定义为空,以后再添加。您可以在这里测试它,我按照您告诉我的方式声明,但仍然得到了错误;变量代码=[“测试”、“测试2”、“测试3”];setItem(“代码”,JSON.stringify(代码));