初学者:提示时提取多个变量

时间:2017-03-19 14:27:02

标签: javascript string object var

我有以下代码:

我想要做的是当我输入提示时,我希望能够输入多个变量并接收它们的输出。我到底该怎么做呢。

例如,当我输入lh0,lh1和lh3时,我希望得到回复000110100110010111101

var outputRef = document.getElementById('outputArea');
var output = " ";

var areas = prompt("Enter no :  "); 

var areas1 = {

        lh0 : "0001101",
        lh1 : "0011001",
        lh2 : "0010011",
        lh3 : "0111101",
        lh4 : "0100011",
        lh5 : "0110001",
        lh6 : "0101111",
        lh7 : "0111011",
        lh8 : "0110111",
        lh9 : "0001011"


};


if (areas1 [ areas ] !== undefined) 
{
    areas = areas1[areas];

}

output = areas;
outputRef.innerHTML = output;

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用Array#split分割用户输入的字符串,例如lh0, lh1, lh2,然后在areas1对象中找到相应的键,并将其值添加到output字符串中。最后,将其显示在DOM中。

var outputRef = document.getElementById('outputArea');
var output = "";

var areas = prompt("Enter no :  ");

var areas1 = {
  lh0: "0001101",
  lh1: "0011001",
  lh2: "0010011",
  lh3: "0111101",
  lh4: "0100011",
  lh5: "0110001",
  lh6: "0101111",
  lh7: "0111011",
  lh8: "0110111",
  lh9: "0001011"
};

areas.split(',').forEach(function(v){
  output += areas1[v.replace(' ', '')];
});

outputRef.innerHTML = output;
<p id="outputArea"></p>

答案 1 :(得分:0)

试试这个:

var outputRef = document.getElementById('outputArea');
var output = " ";

var areas = prompt("Enter no :  "); 

var areas1 = {

        lh0 : "0001101",
        lh1 : "0011001",
        lh2 : "0010011",
        lh3 : "0111101",
        lh4 : "0100011",
        lh5 : "0110001",
        lh6 : "0101111",
        lh7 : "0111011",
        lh8 : "0110111",
        lh9 : "0001011"


};


var results = [];

if (areas) 
{
    areas.split(',').forEach(function(val) {
      results.push(areas1[val]);
    });
}

outputRef.innerHTML = results.join("");
<div id="outputArea">
</div>