从堆栈或表返回数组类型 - Javascript

时间:2018-05-16 08:28:30

标签: javascript arrays

我的代码有问题。也许简单,也许不是 - 首先让我们来看看。

var tab = [];

do{
    var i = 0;
    tab.push(prompt("Write some type of array!"));
    i++;
    
}while(confirm("Next array?"));

for (var i=0; i<tab.length; i++)
    document.write(typeof(tab[i])+"<br>");
<!DOCTYPE HTML>
<HTML>
    <HEAD>
    
        <meta charset="utf-8">
        <meta name="author" content="Donio3d">
    
    </HEAD>
    <BODY>
    
        
    
    </BODY>
    
    <script src="script.js"></script>
    
</HTML>

所以我想从堆栈中返回一种类型的数组。一切都是一串。

有没有办法做到这一点,没有通过IF语句检查?

4 个答案:

答案 0 :(得分:1)

要获取输入的typeof,您必须首先使用Number.isNaN()检查它是否为数字,为简单起见,还使用了Unary plus (+) operator

代码:

const tab = [];
const getInputTyeof  = i => typeof (!Number.isNaN(+i) ? +i : i);

do {
  tab.push(prompt('Write some type of array!'));
} while (confirm('Next array?'));

tab.forEach(input => document.write(getInputTyeof(input) + '<br>'));

答案 1 :(得分:0)

prompt将始终返回string类型,因此您需要使用isNaN()创建自定义逻辑以分隔字符串和整数值。如下所示:

var tab = [];

do{
    var i = 0;
    tab.push(prompt("Write some type of array!"));
    i++;
    
}while(confirm("Next array?"));

var integerType = [];
var stringType = [];
for (var i=0; i<tab.length; i++){
  if(isNaN(tab[i])){
    stringType.push(tab[i]);
  } else {
    integerType.push(tab[i]);
  }

}
console.log('Integer type array ' + integerType);
console.log('String type array ' + stringType);

答案 2 :(得分:0)

由于promt总会在你的例子中返回一个字符串,你必须弄清楚输入是否代表另一种类型,使用类似的东西:

&#13;
&#13;
var tab = [];

do{
    var i = 0;
    tab.push(parseType(prompt("Write some type of array!")));
    i++;
    
}while(confirm("Next array?"));

for (var i=0; i<tab.length; i++){
  document.write((typeof tab[i])+"<br>");
}


function parseType(e){
  if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
    return parseFloat(e);
  }
  return e;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
var tab = [];

do{
    var i = 0;
    tab.push(parseType(prompt("Write some type of array!")));
    i++;
    
}while(confirm("Next array?"));

for (var i=0; i<tab.length; i++){
  document.write((typeof tab[i])+"<br>");
}


function parseType(e){
  if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
    return parseFloat(e);
  }
  return e;
}
&#13;
&#13;
&#13;

喂!这是我正在寻找的。谢谢你的帮助!