简体   繁体   English

如何将字符串转换为对象

[英]How do I convert a string to an object

I'm new to programming and I wanted to develop my skills by working on a small project. 我是编程新手,我想通过一个小项目来发展我的技能。

I am creating a Sudoku app, using HTML/JavaScript. 我正在使用HTML / JavaScript创建一个Sudoku应用程序。 I have a large number (81) of 'div' elements in HTML, and I want to assign content to them using by changing their innerHTML. 我在HTML中有大量(81)'div'元素,我想通过更改innerHTML来为它们分配内容。 Using the two for loops, I go through all 81 variables and re-create their name in 'x', which I then pass to assign_cell() to assemble the code. 使用两个for循环,我遍历所有81个变量并在'x'中重新创建它们的名称,然后我传递给assign_cell()来汇编代码。

puzzle_inc holds the puzzle itself (9..47.8.2..821.. etc; "." denotes empty cell), and I use a counter function to go through its characters one by one, assigning them to each 'div'. puzzle_inc持有拼图本身(9..47.8.2..821 ......等;“。”表示空单元格),我使用计数器函数逐个查看它的字符,将它们分配给每个'div'。

After much testing and searching, I found out that my problem is that x is of 'string' type and the code in assign_cell() will not work. 经过大量测试和搜索,我发现我的问题是x是'string'类型,而assign_cell()中的代码将不起作用。 In this case, x will always be equal to something like "c01". 在这种情况下,x将始终等于“c01”。

What I've been trying to do is to convert x to an object type. 我一直在尝试做的是将x转换为对象类型。 I have tried using JSON.parse() to fix the issue but probably due to my lack of knowledge in the field I have been unsuccessful. 我已经尝试使用JSON.parse()来解决问题,但可能是因为我在该领域缺乏知识,但我没有成功。

I'm not sure how else to approach this but any help would be really appreciated. 我不确定如何处理这个问题,但任何帮助都会非常感激。

Thank you. 谢谢。

function assign_cell(flag, arr1, arr2) {
    if(flag === 1) {
        arr1.innerHTML = puzzle_inc[arr2];
    } else if(flag === 2) {
        arr1.innerHTML = null;
    } else {
        alert("Error in function assign_cell()");
    }   
}

for(var i = 0; i < 9; i++){
    for(var k = 0; k < 9; k++){
        var a = counter();
        var x = "c"+i+k;
        if(puzzle_inc[a] != '.') {
            assign_cell(1, x, a);
        } else {
            assign_cell(2, x, a);
        }
    }
}

EDIT: I've been asked for the whole code, to better help answer my question. 编辑:我被要求提供整个代码,以便更好地帮助回答我的问题。 Please find it below. 请在下面找到它。 Thank you for the answers! 谢谢你的答案!

PHP JS PHP JS

have you tried eval() 你试过eval()吗?

var stringval='[1,2,3]';
var value=eval(stringval);
console.log(value);//=>[1, 2, 3]

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

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