要将JavaScript中的字符串数组转换为数字数组,可以使用map()
函数结合parseFloat()
或者Number()
函数。以下是一个例子:
<template>
<div>
<button @click="refreshComponent">刷新组件</button>
<my-component :key="componentKey"></my-component>
</div>
</template>
<script>
import { ref } from 'vue';
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent
},
setup() {
const componentKey = ref(0);
const refreshComponent = () => {
// 改变key值来强制重新渲染组件
componentKey.value++;
};
return {
componentKey,
refreshComponent
};
}
};
</script>
如果你确认字符串数组中的所有元素都能成功转换为数字,也可以使用parseFloat()
:
// 字符串数组
var stringArray = ["1.5", "2", "3.14", "4", "5"];
// 转换为数字数组
var numberArray = stringArray.map(parseFloat);
console.log(numberArray); // 输出: [1.5, 2, 3.14, 4, 5]
请注意,如果数组中的某些字符串无法转换为数字(例如包含非数字字符),使用Number()
或parseFloat()
会返回NaN
。如果这种情况是不期望的,你可能需要在map()
回调中添加额外的检查来处理这种情况。