Javascript:避免字符串到整数或浮点类型转换与空或未定义变量的异常?

2022-01-12 00:00:00 type-conversion javascript
  • javascript(V8 引擎)
  • 谷歌浏览器
  • 继承了带有大量数字变量类型转换的 javascript 代码.
  • 如何可靠地将 javascript 字符串类型转换为数字变量(浮点数和整数),并且仍然避免由于未声明或空值而导致脚本停止异常?

Tymac 继承了一些 javascript 代码,这些代码需要对变量进行大量类型转换以将浮点数转换为整数到字符串以及这三种类型之间的大量排列.

Tymac has inherited some javascript code that requires a lot of type casting of variables to float to integer to string and numerous permutations between these three types.

问题是,变量被不规则地声明或定义,从而引入了不可预测的势.此外,代码的排列方式很难将其全部整理出来.

The problem is, the variables are declared or defined irregularly, which introduces potential unpredictably. Also, the code is arranged in such a way to make it difficult to sort it all out.

我们的目标是在变量声明因代码设置方式而事先不知道时,提出一种风险证明"方法来在浮点整数字符串之间进行类型转换.

The goal is to come up with a 'risk proof' way to type-cast variables between float-integer-string when the variable declarations are not known in advance because of the way the code is set up.

推荐答案

问题

在变量可能未全部声明或可能导致 Javascript 异常的情况下,您希望可靠地处理浮点、整数和字符串类型之间的类型转换.

Problem

You want to reliably handle type cast conversion between float, integer, and string types reliably in cases where the variables may not all be declared or may otherwise potentially cause a Javascript exception.

如果可能,请确保至少在尝试类型转换之前声明所有变量.

If at all possible, make sure all variables are at least declared before attempting a type cast conversion.

此外,了解如何处理 null 并了解 Javascript 中的相等测试.

Also, understand how to handle nulls and understand equality testing in Javascript.

在这个 Javascript 场景中进行健壮类型检查的一种简单方法是避免:

One easy way to do robust type-checking in this Javascript scenario is to avoid:

  • 未声明的变量
  • Javascript 对象(又名字典)上未声明的属性
  • 空值
  • NaN 值

这是一个简单而快速的概述:

Here is a simple and quick overview:

//
var vfftest       = 0.05;                       // float
var viitest       = 3000;                       // integer
var vssblank      = '';                         // empty string
var vssnonblank   = 'hello';                    // non-empty string
var vddempty      = {};                         // dictionary with no name-value pairs
var vddnonempty   = {'alpha':1,'bravo':'two'};  // dictionary with name-value pairs
var vnull         = null;                       // null

// check boolean
console.log( (vssnonblank) ? 'true' : 'false' ); // true
console.log( (vssblank)    ? 'true' : 'false' ); // false
console.log( (vfftest)     ? 'true' : 'false' ); // true
console.log( (viitest)     ? 'true' : 'false' ); // true
console.log( (vnull)       ? 'true' : 'false' ); // false
console.log( (vddempty)    ? 'true' : 'false' ); // true
console.log( (vddnonempty) ? 'true' : 'false' ); // true
console.log( (vnoExisto)   ? 'true' : 'false' ); // EXCEPTION

// check toString
console.log( (vssnonblank).toString()  );  // hello
console.log( (vssblank).toString()     );  //
console.log( (vfftest).toString()      );  // '0.05'
console.log( (viitest).toString()      );  // '3000'
console.log( (vnull).toString()        );  // EXCEPTION
console.log( (vddempty).toString()     );  // [object Object]
console.log( (vddnonempty).toString()  );  // [object Object]
console.log( (vnoExisto).toString()    );  // EXCEPTION

// check parseFloat
console.log( parseFloat(vssnonblank) ); // NaN
console.log( parseFloat(vssblank) );    // NaN
console.log( parseFloat(vfftest) );     // 0.05
console.log( parseFloat(viitest) );     // 3000
console.log( parseFloat(vnull) );       // NaN
console.log( parseFloat(vddempty) );    // NaN
console.log( parseFloat(vddnonempty) ); // NaN
console.log( parseFloat(vnoExisto) );   // EXCEPTION

// check parseInt
console.log( parseInt(vssnonblank) );  // NaN
console.log( parseInt(vssblank) );     // NaN
console.log( parseInt(vfftest) );      // 0
console.log( parseInt(viitest) );      // 3000
console.log( parseInt(vnull) );        // NaN
console.log( parseInt(vddempty) );     // NaN
console.log( parseInt(vddnonempty) );  // NaN
console.log( parseInt(vnoExisto) );    // EXCEPTION

// check typeof
console.log(typeof vssnonblank);       // string
console.log(typeof vssblank);          // string
console.log(typeof vfftest);           // number
console.log(typeof viitest);           // number
console.log(typeof vddempty );         // object
console.log(typeof vddnonempty );      // object
console.log(typeof vnull);             // object
console.log(typeof vnoExisto);         // 'undefined'

陷阱

  • <未声明>为 parseInt parseFloat 和 .toString() 引发异常
  • null.toString() 抛出异常
  • parseInt(null) 和 parseFloat(null) 返回 NaN
  • 如果可以,至少要确保所有变量都已声明.这将防止未声明的值出现异常,但不会出现空值.
  • 即使您使用 try-catch 块,并确保声明了所有变量,您仍然需要处理 null 异常,这些异常可能会导致您的代码停止.
  • 以下链接提供了与 Javascript 中的类型转换和比较相关的其他详细信息:

    The following links provide additional details relevant to type-cast and comparison in Javascript:

    • 在 ToString() 之前检查 null
    • 什么是最检查 JavaScript 变量是否为空的可靠方法?
    • 等于运算符 (== vs ===) 应该用在 JavaScript 比较中吗?
    • 如何在javascript中将字符串转换为浮点数?
    • JavaScript 类型转换
    • 在抛出异常时不要停止 JavaScript
    • 在 JavaScript 中查找变量类型

相关文章