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