js数据类型转换

转Boolean

在条件判断时,除了  undefined ,  null ,  false ,  NaN ,  '' ,  0 ,  -0 ,其他所有值都转为  true ,包括所有对象。

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">点击</el-button>
  </section>
</template>
<script>
  export default {
    data() {
      return {
        val: {
          a: '1',
          b: 1,
          c: [],
          d: {},
          e: function () {
          },
          f: undefined,
          g: null,
          h: false,
          i: '',
          j: 0,
          k: -0
        }
      }
    },
    methods: {
      get() {
        for (let aa in this.val) {
          if (this.val[aa]) {
            console.log(this.val[aa]);
          }
        }
      }
    }
  };
</script>

对象转基本类型

对象在转换基本类型时,首先会调用  valueOf  然后调用  toString 。并且这两个方法你是可以重写的。

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">点击</el-button>
  </section>
</template>
<script>
  export default {
    data() {
      return {
      }
    },
    methods: {
      get() {
        let a = {
          valueOf() {
            return 66;
          },
          toString() {
            return '1';
          }
        };
        console.log(1 + a);
        console.log(String(a));
      }
    }
  };
</script>

当然你也可以重写  Symbol.toPrimitive  ,该方法在转基本类型时调用优先级最高。

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">点击</el-button>
  </section>
</template>
<script>
  export default {
    data() {
      return {
      }
    },
    methods: {
      get() {
        let a = {
          valueOf() {
            return 66;
          },
          toString() {
            return '1';
          },
          [Symbol.toPrimitive]() {
            return 99;
          }
        };
        console.log(1 + a);
        console.log(String(a));
      }
    }
  };
</script>

嗯,就酱~~

https://www.cnblogs.com/chuhui/archive/2018/12/03/10060071.html

原文地址:https://www.cnblogs.com/jin-zhe/p/10069974.html