


Introduction to methods of converting objects into strings, numbers and Boolean values in js (example)
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
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 |
Undefined | Throw TypeError exception |
Null | Throws TypeError exception |
Number | Create 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 == '1');//true
三、对象转化成布尔值:
对象在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
总结:
在JavaScript中,对象有三个转换,这取决于具体情况:
字符串输出,使用toString 。
数字:数学函数,操作符,使用valueOf 后使用 toString 。
布尔值:转化为true。
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
