


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 (>, =,
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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
