1. 统计一个数组中,每个值的个数
var cards = [1, 2, 3, 4, 3, 2, 1, 4, 5]
var dict = {};
for(var i = 0; i < cards.length; i ++){
dict[cards[i]] = dict[cards[i]] ? dict[cards[i]] + 1 : 1;
}
2. 比较两个对象的内容是否相同
var compareOBJ = function (obj1, obj2) {
var o1 = obj1 instanceof Object;
var o2 = obj2 instanceof Object;
if(!o1 || !o2)
return obj1 === obj2;
if(Object.keys(obj1).length !== Object.keys(obj2).length)
return false;
for(var attr in obj1) {
var to1 = obj1[attr] instanceof Object;
var to2 = obj2[attr] instanceof Object;
if(to1 && to2) {
compareOBJ(obj1[attr], obj2[attr]);
}else if(obj1[attr] !== obj2[attr]) {
return false;
}
}
return true;
};
3. 判断手牌数组是否同花
var isSameColor = function (cardArr) {
var dict = {};
for(var i = 0; i < cardArr.length; i ++) {
var cd = cardArr[i];
var ten = Math.floor(cd / 10);
dict[ten] = dict[ten] ? dict[ten] + 1 : 1;
}
return Object.keys(dict).length === 1;
};