JS 数组中数字和字符串数字表示之间的差异
问题
我们要求编写一个 JavaScript 函数,该函数采用数字的混合数组和整数的字符串表示形式。
我们的函数应该将字符串整数相加,然后从非字符串整数的总和中减去它。
示例
以下是代码 −
const arr = [5, 2, '4', '7', '4', 2, 7, 9];
const integerDifference = (arr = []) => {
let res = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(typeof el === 'number'){
res += el;
}else if(typeof el === 'string' && +el){
res -= (+el);
};
};
return res;
};
console.log(integerDifference(arr));输出
以下是控制台输出 −
10
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP