文章目录
- 1.在数组中找到匹配项,然后创建新对象
- 2.对象转JSON字符串
- 3.JSON字符串转JSON对象
- 4.有个响应式对象,然后想清空所有属性
- 5.判断参数不为空
- 6.格式化字符串
- 7.解析数组内容用逗号拼接
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"