2013-03-23 70 views
0

我在JavaScript中有4位數的表示形式,代表一天中的4次(上午,下午,晚上,晚上)。檢查某位置的位是否爲1

所以我們說我有十進制數字13(1101),它表示一些動作必須在夜間,傍晚和早上(不是下午,因爲第二位是0)完成。

我到目前爲止所做的是獲取4位數字代表當天(1000是夜晚,0100是夜間,0010是下午,0001是早上),我想要做的是創建一個函數,比較2個數字,並且如果某個位置上的位等於1,則返回true。

我意識到位運算符,但我試圖使用它們,但仍然沒有運氣。

+0

'(X(1個<< bit_pos))= 0' – zch 2013-03-23 19:15:15

+0

' !!(x&(1 << bit_pos))' – average 2013-03-23 19:16:03

回答

2

是的,按位進行。您可以使用簡單的位掩碼測試。

var PERIODS_OF_DAY = { 
    MORNING: 1, AFTERNOON: 2, EVENING: 4, NIGHT: 8 
}; 

var isPeriodOfDay = function(number, period) { 
    return !!(number & period); 
}; 

測試數13

for (period in PERIODS_OF_DAY) { 
    if(PERIODS_OF_DAY.hasOwnProperty(period)) { 
     console.log(period + ":", isPeriodOfDay(13, PERIODS_OF_DAY[period])); 
    } 
} 

MORNING: true 
AFTERNOON: false 
EVENING: true 
NIGHT: true 
+0

它的工作,謝謝。 – Pacha 2013-03-23 19:37:14

0
function getTimes (value, time) { 
    var times = ["morning", "afternoon", "evening", "night"]; 

    if (time) { 
     return !(~value & 1 << times.indexOf(time)); 
    } 

    return times.filter(function(time, i) { return !(~value & 1 << i); }); 
} 

console.log(getTimes(13, "afternoon")); // false 
console.log(getTimes(13)); // ["morning", "evening", "night] 

JSFiddle

相關問題