文章目錄
- 1.在數組中找到匹配項,然后創建新對象
- 2.對象轉JSON字符串
- 3.JSON字符串轉JSON對象
- 4.有個響應式對象,然后想清空所有屬性
- 5.判斷參數不為空
- 6.格式化字符串
- 7.解析數組內容用逗號拼接
- 8.刷新整個頁面
1.在數組中找到匹配項,然后創建新對象
const modifiedRecords = ref([])
const handleBlur = (record) => {const index = modifiedRecords.value.findIndex(item => item.serialNo === record.serialNo);if (index !== -1) {modifiedRecords.value[index] = { ...record };} else {modifiedRecords.value.push({ ...record });}
}
在 JavaScript 中,{ ...record }
是一種對象展開運算符(spread operator)的用法。它用于將一個對象的所有可枚舉屬性復制到一個新對象中。具體來說,{ …record } 的作用是創建一個新的對象,該對象具有與 record 相同的屬性和屬性值。
這里的 { ...record } 確保了更新時不會直接修改 record 對象,而是創建了一個新的對象,這在處理狀態管理和數據更新時是一個良好的實踐。
2.對象轉JSON字符串
JSON.stringify(response.principal)
3.JSON字符串轉JSON對象
JSON.parse(principal)
4.有個響應式對象,然后想清空所有屬性
const checkedList = reactive({})
Object.keys(checkedList).forEach(key => {delete checkedList[key];
});
5.判斷參數不為空
if (data.note1 == undefined || data.note1 == null || data.note1 == "") {param.remark = "";
}
6.格式化字符串
在 Java 中,String.format 和 MessageFormat 都可以用于格式化字符串,但它們的用法和適用場景有所不同。下面是對這兩種方法的詳細比較和用法示例。
- String.format
String.format 是一個靜態方法,用于創建格式化字符串。它使用 C 語言風格的格式說明符,適合于簡單的字符串格式化。
用法示例
String name = "Alice";
int age = 30;// 使用 String.format 進行格式化
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString); // 輸出: My name is Alice and I am 30 years old.
格式說明符
- %s:字符串
- %d:整數
- %f:浮點數
- %x:十六進制整數
- MessageFormat
MessageFormat 是一個用于國際化的類,它允許你在字符串中使用占位符,并根據提供的參數進行格式化。它適合于需要處理多語言和復雜格式的場景。
用法示例
import java.text.MessageFormat;String name = "Alice";
int age = 30;// 使用 MessageFormat 進行格式化
String pattern = "My name is {0} and I am {1} years old.";
String formattedMessage = MessageFormat.format(pattern, name, age);
System.out.println(formattedMessage); // 輸出: My name is Alice and I am 30 years old.
占位符
{0}
:第一個參數{1}
:第二個參數- 可以繼續使用 {2}、{3} 等來引用后續參數。
主要區別
格式化語法
:- String.format 使用 % 符號和格式說明符。
- MessageFormat 使用 {} 占位符。
國際化
:- MessageFormat 更適合用于國際化,因為它支持格式化日期、數字和貨幣等更復雜的格式。
- String.format 主要用于簡單的字符串格式化。
性能
:- 在簡單的格式化場景下,String.format 可能更快,因為它的實現相對簡單。
- MessageFormat 在處理復雜的國際化需求時更為強大,但可能在性能上稍遜一籌。
選擇建議
- 如果你只需要進行簡單的字符串格式化,并且不需要國際化支持,可以使用 String.format。
- 如果你的應用需要處理多語言,或者需要格式化日期、貨幣等復雜類型,建議使用 MessageFormat。
總結
- String.format: 用于簡單的字符串格式化,適合快速格式化。
- MessageFormat: 用于國際化和復雜格式化,適合需要處理多種格式的場景。
7.解析數組內容用逗號拼接
我有個[“0”, “1”, “2”, “3”, “4”],我想輸出:“0,1,2,3,4”
const warningNotice = ["0", "1", "2", "3", "4"];
const warningNoticeString = warningNotice.join(','); // 使用逗號作為分隔符
console.log(warningNoticeString); // 輸出: "0,1,2,3,4"
8.刷新整個頁面
總結
:類似于執行F5刷新按鈕
window.location.reload();