首字母置为大写
replaceToUpperCase: function (str) { // 首字母置为大写
var reg = /\b(\w)|\s(\w)/g; // \b判断边界\s判断空格
return str.replace(reg, function (m) {
return m.toUpperCase()
});
},
示例代码:
var test = ‘abc’;
var test1 = Vue.tpUtil.replaceToUpperCase(test);
console.log(test1);//Abc
克隆
cloneObj: function (obj, flag) {
var str, newobj = typeof obj === 'object' && isNaN(obj.length) ? [] : {};
if (typeof obj !== 'object') {
return;
} else if (window.JSON) {
str = JSON.stringify(obj), // 系列化对象
newobj = JSON.parse(str); // 还原
if (flag) {
for (var name in newobj) {
newobj[name] = '';
}
}
} else {
for (var i in obj) {
newobj[i] = typeof obj[i] === 'object' ?
this.cloneObj(obj[i]) : null;
}
}
return newobj;
},
数组转对象
arrayToObject: function (key, value, data) {
if (!key || !data) {
return {};
}
var d = {};
for (var name in data) {
d[data[name][key]] = data[name][value];
}
return d;
},
示例:
Var b = [{ type: 'Main1', comName: 'index1' },
{ type: 'Main2', comName: 'index2' }];
console.log(Vue.tpUtil.arrayToObject('type', b));
// {Main1: { type: 'Main1', comName: 'index1' },
Main2: { type: 'Main2', comName: 'index2' },
比较一组对象是否存在于另一组对象
compareObject: function (origin, target) {
if (target && typeof target === 'object') {
if (typeof origin !== 'object') {
return false
} else {
if (JSON.stringify(origin) === JSON.stringify(target)) {
return true
} else {
return false
}
}
} else {
return origin === target
}
},
示例
var a = { b: '333', c: 'eeee', t: '22' }, b = { b: '333', c: 'eeee' }; console.log(Vue.tpUtil.compareObject(a, b));\\ true