简体   繁体   English

试图在Javascript中加入二维数组

[英]Trying to join a two-dimensional array in Javascript

I'm trying to convert a two-dimensional array to a string in order to store it in the localStorage array. 我正在尝试将二维数组转换为字符串,以便将其存储在localStorage数组中。 However, there is something wrong with this code I cannot identify: 但是,我无法识别的代码有问题:

for(x in array) {
    if(array[x] instanceof Array) {
        array[x] = array[x].join("`");
    }
}
var string = array.join("@");
localStorage[key] = string;

Does anyone have an idea what I'm doing wrong? 有谁知道我做错了什么?

As for what's wrong, by multidimensional array I mean array[0][1] etc. When input into localStorage, all the 'string' is reduced to is @, implying on the other side of the @ there are still arrays. 至于什么是错的,通过多维数组我的意思是数组[0] [1]等。当输入到localStorage时,所有'字符串'都被缩减为@,暗示@的另一边还有数组。

现在这很简单:

[[1,2],[3,4]].map(e => e.join(':')).join(';'); // 1:2;3:4

what is the something that is wrong? 什么是错的? surely, you ucan say what your input is, what you expected, and what the undesired output is? 当然,你可以说你的输入是什么,你期望什么,以及不希望的输出是什么?

At least, if array is indeed an array, you should not use a for..in loop . 至少,如果array确实是一个数组,则不应使用for..in loop That's for objects. 这是对象。 Just use a 只需使用一个

for (var i=0, l=array.length; i<l; i++){
    if (array[i] instanceof Array){
        array[i] = array[i].join("`");
    }
}

JSON is now standard in modern browsers. JSON现在是现代浏览器的标准配置。 You can use it to "stringify" (convert to a JSON string) and "parse" convert from a JSON string. 您可以使用它来“stringify”(转换为JSON字符串)并从JSON字符串“解析”转换。

You can use the JSON.stringify function to convert your 2D array to JSON and stick it in localStorage . 您可以使用JSON.stringify函数将2D数组转换为JSON并将其粘贴到localStorage Then you can use JSON.parse to convert it back to an array. 然后,您可以使用JSON.parse将其转换回数组。

var my2DArray = [[1, 2, 3], [4, 5, 6]];
var stringified = JSON.stringify(my2DArray);
localStorage[key] = stringified;

var backToOriginal = JSON.parse(localStorage[key]);

Javascript doesn't have two dimensional arrays. Javascript没有二维数组。 It has only ragged arrays. 它只有不规则的数组。 Your code works for me for an appropriate input: 您的代码适用于我的适当输入:

array = [[1,2],[3,4]];
for(x in array) {
    if(array[x] instanceof Array) {
        array[x] = array[x].join("`");
    }
}
var string = array.join("@");
alert(string);

Output: 输出:

1`2@3`4

Could you show us what input you are using and what output you get? 你能告诉我们你正在使用什么输入以及你得到了什么输出?

Your code seems to work fine for me, testing in Firefox. 你的代码似乎对我很好,在Firefox中测试。

Is it failing in a specific browser? 它是否在特定浏览器中失败?

var array = [
["a","b"],
["c","d","e"]];
for(x in array) {
    if(array[x] instanceof Array) {
        array[x] = array[x].join("`");
    }
}
var string = array.join("@");
console.log(string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM