通过 js 把 string 数组转 number 数组

要将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()回调中添加额外的检查来处理这种情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值