简体   繁体   English

更改javascript数组格式

[英]change javascript array format

I want to create a linear javascript array like this: 我想创建一个线性javascript数组,如下所示:

A = ["1","2","3"];
B = ["4","5","6"];

From Data that is already a long javascript array but is formatted like this: 来自已经是一个长javascript数组但格式如下的数据:

var A = [];
var B = [];
A[0] = "1";
B[0] = "4";
A[1] = "2";
B[1] = "5";
A[2] = "3";
B[2] = "6";

What is the easiest way to convert the javascript array from the 2nd example to the 1st? 将javascript数组从第二个示例转换为第一个示例的最简单方法是什么?

With the code in the 1st format the filesize is smaller, and the data easier to edit. 使用第一种格式的代码,文件大小更小,数据更易于编辑。

Just put the second code in the console and then type 只需将第二个代码放入控制台,然后键入

console.log('var A =', A);
console.log('var B =', B);

you will get in the console the text you need to paste back in your code.. 您将在控制台中获得需要粘贴回代码中的文本。

If your variables are global try running 如果您的变量是全局变量,请尝试运行

console.clear();
for (var global in window){
    if (window.hasOwnProperty(global)){
        if (Array.isArray(window[global])){
           console.log( 'var',global, '=', window[global] );
        }
    }
}

after your script. 在您的脚本之后。 ( it might show other arrays as well, just copy those you want.. ) 它也可能显示其他数组,只需复制所需的数组即可。

You can get the short text form of any object using the JSON.stringify [MDN] function: 您可以使用JSON.stringify [MDN]函数获取任何对象的短文本形式:

JSON.stringify(A);
// returns '["1","2","3"]';

maybe you should do something like this and copy paste the string from the console: 也许您应该执行以下操作,然后从控制台复制并粘贴字符串:

var A = [];
var B = [];
A[0] = "1";
B[0] = "4";
A[1] = "2";
B[1] = "5";
A[2] = "3";
B[2] = "6";

function getOutputStr(arr) {
    var output = '[';
    for (var i = 0; i < arr.length; i++) {
        output += '"' + arr[i] + '",'
    }

    output = output.substring(0, output.length - 1);
    output += ']';
    return output;
}
console.log(getOutputStr(A));
console.log(getOutputStr(B));

Fiddle 小提琴

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

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