Home > Web Front-end > JS Tutorial > body text

Introduction to methods of converting objects into strings, numbers and Boolean values ​​in js (example)

不言
Release: 2018-09-15 17:30:28
Original
2233 people have browsed it

The content of this article is about the introduction (examples) of converting objects into strings, numbers and Boolean values ​​in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

1. Convert the object into a string:

Rules:

1. If the object has a toString method, call the method and return the corresponding result; (the code is usually Will be executed until this point, because there is a toString method in all objects)

2. If the object has a valueOf method, call the method and return the corresponding result;

3. Otherwise throw Exception occurred.

Usually, all objects have a toString method, and built-in objects have their own implementation of the toString method

alert({key: 'value'}) // [object Object]
alert( [1,2] ) // "1,2"
alert( new Date() ) // "Sat Sep 15 2018 15:58:01 GMT 0800 (China Standard Time)"

In interface output, such as alert() and document.write(), toString will be called first. If a scalar or undefined or null cannot be obtained, valueOf will be tried again. If the object is still returned, an error will be reported.
In fact, in the calls to functions such as parseInt(), alert(), document.write(), the type conversion of parameters should be regarded as "passive". It is the implementation of the function that gives priority to calling toString, and Non-data objects automatically call toString.

You can customize toString()

var obj = {
    age:23,
    toString:function(){        
    return this.age;
    }
}
obj.toString();//23
Copy after login

2. Convert objects into numbers

There are two main situations that need to be converted into numbers:

inside the function Parameters need to be numbers, such as: Math.sin(obj) / isNaN(obj) and arithmetic operators: obj;

is used for comparison, such as: obj == 'John'

PS : Type conversion will not occur in the following two comparisons.

a) In strict comparison (===), no type conversion will occur.

b) In non-strict comparison , if the parameters are all objects, no type conversion will occur. Usually, if two objects refer to the same object, true will be returned.

Rules for conversion into numbers:

1. If the object has valueOf method, call the method and return the corresponding result;

2. When the valueOf is still not returned by calling valueOf, the toString method of the object will be called and the corresponding result will be returned;

3. Otherwise an exception is thrown.

The valueOf method of the object returns the object itself, not the string (such as arrays and functions, their valueOf method is inherited from Object.prototype, and the default behavior is to return the object itself), so Will use toString

for object type participation Arithmetic operations and "==" operations are not equal to comparison operations (>, <, >=, <=). Data type conversion occurs automatically. ValueOf is called first. , if valueOf cannot return a scalar (number, string, boolean) and undefined, null,

will continue to call toString. If it still returns object type data, an error will be reported.

Exception for the Date type: In the and == operations, toString takes precedence, which should be the specification's special treatment of this data type.

Supplement: The result of calling valueOf():

Parameter type Return results
UndefinedThrow TypeError exception
NullThrows TypeError exception
NumberCreate a Number object whose internal initial value is the passed parameter value
String Create a String object whose internal initial value is the passed parameter value
Boolean Create a Boolean object whose internal initial value is the passed parameter value
Object The object itself


可以重写对象的valueOf()方法(百度一道面试题,定义一个对象,使obj == '1' ,结果为true):

var obj = {
    valueOf: function(){       
    return 1;
    }
};
console.log(obj == &#39;1&#39;);//true
Copy after login

三、对象转化成布尔值:

对象在JS中总是返回true

根据上述,对象在相等性判断中如何转变?

在布尔上下文中, a是true , b是false,a == b,这是可能的 。

[] == ![] //true

内部的转化步骤:

1、右边是![],将会被转换成一个布尔值,[]为true,取非为false,此时表达式变成:

[]==false;

2、按照规则,右边是布尔值,将false转换成0,左边是数组,数组也将进行数字转换,先调用valueOf(),不能转化成原始值,再用toString(),转换为0

0 == 0

3、结果为true

补充 == 和!=判断规则(注意: ===!== 和 对象==对象 这三种情况不会进行类型转换):

如果有一个操作数是布尔值,则在比较相等性之前先将其转换为数值----false转化为0,true转化为1;

如果有一个数是字符串,另一个操作数是数值,将字符串转化成数值;

如果一个操作数是对象,另一个操作数不是对象,将对象转化为基本操作类型(先valueOf()再toString(),均不能得到基本类型的值则会报错),再比较。

所以,对象在相等性判断中:

若两边都是对象,不会进行类型转换,为同一个引用才会返回true

若只有一边为对象,则会先调用对象的valueOf()方法,不能返回基本类型,再调用对象的toString()方法,还是不能就会报错,否则用转化后的基本类型值继续进行判断

举例,感受下~:
[]==[]//false
[]==false//true
!![]//true
[]==![]//true
Copy after login

总结:

在JavaScript中,对象有三个转换,这取决于具体情况:

字符串输出,使用toString 。

数字:数学函数,操作符,使用valueOf 后使用 toString 。

布尔值:转化为true。

 相关推荐:

js中json字符串和json对象互相转化的方法实现

js中json对象和字符串相互转化操作实例

The above is the detailed content of Introduction to methods of converting objects into strings, numbers and Boolean values ​​in js (example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template