2017-02-03 10 views
0

私は秒単位で合計数値を取得したいというような文字列(時間)を01:02:3としたい。だから、期待される出力は3723.JavaScriptを使ってセミコロンで区切られた文字列を変換する

const time = "1:02:3"; 

const timeNumeric = time.split(':').map(item => { 
    return Number(item) 
}); 

function total() { 
    var totalTime = 0; 
    if (timeNumeric.length = 3) { 
    const num1 = timeNumeric[0] * 3600 
    const num2 = timeNumeric[1] * 60 
    const num3 = timeNumeric[2] 
    totalTime = num1 + num2 + timeNumeric[2] 
    } else if (timeNumeric.length == 2) { 
    const num2 = timeNumeric[1] * 60 
    const num3 = timeNumeric[2] 
    totalTime = num2 + num3 
    } else if (timeNumeric.length == 1) { 
    const num3 = timeNumeric[2] 
    totalTime = num3 
    } else { 
    console.log('nothing') 
    } 
    console.log(totalTime) 
} 

に注意してくださいだろう、文字列の値は常に3つの数字ではないかもしれません、そして、第三のオプション値が任意の計算を必要としないであろう、2:45または30である可能性があります。

+0

何が問題なのですか? – Hosar

+0

お詫び申し上げます。もっと理にかなった質問を編集しました。 – calebo

+0

文字列が「2:45」の場合は、2分45秒か2時間45分ですか? –

答えて

1

あなたのコードは現在の番号以外は正しいです。 * JavaScriptを使用すると、数値に変換しようとします。しかし、+ JavaScriptを使用すると、2つの変数のうちの1つが文字列の場合、JavaScriptはStringに変換しようとします。

var getSeconds = function(time) { 
    return time.split(':').reduce(function(prev, curr) { 
     return prev * 60 + parseInt(curr, 10) 
    }, 0) 
} 

var total = getSeconds('01:02:03') 
var total2 = getSeconds('2:34') 

console.log(total, total2) // 3723 154 
1

reduce関数を使用して乗算するには、分割文字列を数値に変換する必要があります。このようなもの:

const strNums = "01:02:3"; 
const multiplier = 3; 

const arrayStrNums = strNums.split(':').map(item => { 
    return Number(item) * multiplier; 
}); 

const total = arrayStrNums.reduce((a, b) => { 
    return a + b; 
}) 

console.log(total); 
+1

一般に私は 'parseInt(item、10)'を好むでしょう。 'Number'のような振る舞いが優れていると、' + item'も 'Number'に強制して短くなります。 – ephemient

関連する問題