本文內(nèi)容不是解決問題,而是記錄一些常用的方法行拢,代碼用的是TS語言祖秒。
第一個:保留幾位小數(shù),傳入數(shù)字和精確度舟奠,傳出新數(shù)字
/**
* @param num 原數(shù)字
* @param precision 精確度(10^n代表保留n位小數(shù)竭缝,例如,precision = 100代表保留2位小數(shù))
*/
public static NumberFix(num: number, precision: number): number {
return Math.floor(num * precision) / precision;
}
第二個:計算字符串長度沼瘫,輸入字符串抬纸,返回長度
public static GetStringLength(text: string): number {
let count: number = 0;
// stringObject.split傳入空字符串 (""),則每個字符之間都會被分割
let newStr: string[] = text.split("");
for (let i:number = 0; i < newStr.length; i++) {
if (newStr[i].charCodeAt(0) < 299) {
// 普通字符
count++;
}else {
// 漢字
count += 2;
}
}
return count;
}
第三個:判斷此值在不在數(shù)組中耿戚,傳入值和數(shù)組湿故,傳出判斷結果
public static IsParmInList(parm1: any, list: any[]): boolean {
let isIn:boolean = false;
if (!Array.isArray(parm1) && list != null && Array.isArray(list) && list.length > 0) {
for (let i:number = 0;i < list.length; i++) {
if (parm1 === list[i]) {
isIn = true;
break;
}
}
}
return isIn;
}
第四個:CocosCreator數(shù)據(jù)存儲
public static GetLocalStorageData(key: string): string {
return cc.sys.localStorage.getItem(key);
}
public static SetLocalStorageData(key: string, value: string): void {
cc.sys.localStorage.setItem(key, value);
}
第五個:替換文字中的占位符,替換2個膜蛔,傳入(字符串/占位符1/占位符2/替換字符串1/替換字符串2)坛猪,傳出新字符串
public static getReplaceString2(originStr: string, placeholder1: string, placeholder2: string, replaceStr1: string, replaceStr2: string) : string{
let str: string = originStr;
str = str.replace(placeholder1, replaceStr1);
str = str.replace(placeholder2, replaceStr2);
return str;
};
第五個:時間戳(秒級)轉換為年月日時分秒,格式:(2020.02.02 02:02:02)
public static FormatTimeStamp(timeStamp: number): string {
let date: Date = new Date(timeStamp * 1000);
let year: number = date.getFullYear();
let month: number = date.getMonth() + 1;
let day: number = date.getDay();
let hour: number = date.getHours();
let minute: number = date.getMinutes();
let second: number = date.getSeconds();
let str: string = "";
str += year + ".";
str += (month < 10) ? ("0" + month + ".") : (month + ".");
str += (day < 10) ? ("0" + day + " ") : (day + " ");
str += (hour < 10) ? ("0" + hour + ":") : (hour + ":");
str += (minute < 10) ? ("0" + minute + ":") : (minute + ":");
str += (second < 10) ? ("0" + second) : second;
return str;
};