typeof variable!=='undefined'将变量转换为字符串?

时间:2018-02-21 17:48:34

标签: javascript

如果typeof运算符返回字符串,变量third将成为字符串。当javascript进入for循环时,javascript如何将third更改回数字

function range(start, end, third){
  var numberlist = [];
 if(typeof third !== 'undefined'){ 
    if (start < end){
      for (var count = start; count < end; count++){
    numberlist.push(count + third);
    }
  } 
 }
}
console.log(range(1,10,2));

3 个答案:

答案 0 :(得分:1)

third在这里不会成为字符串。

typeof third !== 'undefined'可以改写为(typeof third) !== 'undefined',或者更详细:

let m = typeof(third)
if(m !== 'undefined') { }

在任何一种情况下,它都返回一个字符串,而不是将该字符串分配给变量third

如果您希望return numberlist有意义,您还应该在功能结束时console.log(range(1,10,2))

答案 1 :(得分:0)

这里的范围只是填充数组,但它永远不会返回,因此"undefined"报告return numberlist;。在函数末尾添加以下内容:#standardSQL WITH t AS ( SELECT 1519152103659000 AS ts UNION ALL SELECT 1519152113786000 UNION ALL SELECT 1519152118754001 UNION ALL SELECT 1519152118972002 UNION ALL SELECT 1519152119026003 ) SELECT ts AS timestamp_in_microseconds_as_int64, TIMESTAMP_MICROS(ts) AS timestamp_as_timestamp, DATE(TIMESTAMP_MICROS(ts)) AS dt FROM t

答案 2 :(得分:0)

我会试试这个:

在此处查看:https://jsfiddle.net/wpfcv401/2/

function range(start, end, third) {
  var numberlist = [];

  if(third) {            //if third is NOT null and not undefined
     if(isNaN(third)) {  //if third is not a number
        third = parseInt(third);
     }
     if(!isNaN(third)){
        if (start < end){
           for (var count = start; count < end; count++){
              numberlist.push((count + third));
              alert('pushing ' + (count + third));
           }
        }
      }
   }
}
console.log(range(1,3,2));