想要避免JavaScript中的评估-

use*_*460 5 javascript eval blockly

我正在使用JavaScript将字符串转换为Google Blockly块

输入字符串类似于"Hello %s World"-在其中%s定义字符串输入。我需要将其转换为:

Blockly.Blocks['blockname'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Hello ")
        .appendField(new Blockly.FieldTextInput("input1"), "")
        .appendField(" World");
  }
};
Run Code Online (Sandbox Code Playgroud)

但是我不确定在不使用eval()的情况下如何实现这一目标,并且由于输入字符串来自用户,因此我知道使用eval()并不是一个好主意。

我当前的代码是:

currentLine = blockText[x].split(/(%s)/);
for( var y = 0; y < currentLine.length; y++ )
{
  if( currentLine[y] == "" )
  {
    //do nothing
  }
  else if( currentLine[y] == "%s" )
  {
    //create a input
  }
  else
  {
    //create a label
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我不确定如何创建所需的Blockly代码,而无需在字符串中构建JavaScript,然后在末尾使用eval()。

有人可以帮我吗?

Nit*_*iya 2

您可以创建一个自定义通用块,无需任何输入,如下所示 -

  Blockly.Blocks['generic_block'] = {
    init: function() {
      this.jsonInit({
        message0: '',
        colour: '230'
      });
    }
  };
Run Code Online (Sandbox Code Playgroud)

现在您可以通过代码创建该块的新实例。根据您的 JS 字符串解析,您可以在该块内创建输入和字段,如下所示 -

var lineBlock=yourBlocklyWorkspace.newBlock('generic_block');         // create new instance of generic block
var input=lineBlock.appendDummyInput();                               // create a dummy input
var blockText="Hello %s World";                                       // one line of the JS code
var currentLine = blockText.split(/(%s)/);                            // split every word
for( var y = 0; y < currentLine.length; y++ ) {                       // loop through each word
  if(currentLine[y]==='%s') {                                         // if the word is %s, then append input field
    input.appendField(new Blockly.FieldTextInput('input'+y));         // input+y is the name of the field
  } else {                                                                         // else just append label field
    var labelField=new Blockly.FieldLabel('label'+y);                         // label+y is the name of the field
    labelField.setValue(currentLine[y]);                                          // set the label value to the word
    input.appendField(labelField)
  }
}
Run Code Online (Sandbox Code Playgroud)