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

JavaScript Learning Summary [3] JS Object

黄舟
Release: 2017-02-09 14:40:39
Original
838 people have browsed it

Everything in JS is an object, and provides multiple built-in objects, such as String, Array, Date, etc., and also supports custom objects. An object is just a special type of data that has properties and methods. Properties are values ​​associated with the object, and methods are actions that can be performed on the object.

1. String object

String object is used to process text, that is, string. A string is used to store a series of characters. Usually JS strings are primitive values. You can use variable declarations or you can use the new keyword to define a string as an object. In JS, it is not recommended to use the new keyword to create objects. . The original value string has no properties and methods, but you can use the properties and methods of JS, because JS can treat the original value as an object when executing properties and methods.

 You can use JS’s built-in length property to calculate the length of a string. For example:

var str = "abcdefghijklmnopqrstuvwxyz";
alert(str.length);    //返回:26
Copy after login

The following are some commonly used methods for strings:

 (1), charAt()

str.charAt(index) Returns the character at the specified index position, That is to get a certain character of the string.

 (2), concat()

str1.concat(str2, str3, ...., strN) Used to concatenate two or more strings and return the concatenated characters string.

 (3), indexOf()

str.indexOf(a certain character, strat) Returns the position where a certain character first appears in the string starting from the specified position. The second parameter can Select, specifies the position to start searching in the string. Its legal values ​​are 0 to the length of the string -1: str.length-1. If this parameter is not set, the search starts from the first character of the string. The return value is a numeric value. If it is found, it returns the position where the character first appears. If it is not found, it returns -1.

 (4), search()

Search(str/RegExp) Returns the position where a certain character first appears in the string. The parameter is a character or regular expression. The effect is better when combined with the regular expression. OK, the return value is a numeric value. If there is no match, -1 is returned.

The difference between indexOf() and search():

Both methods return the position where the character first appears, but using search() with regular expressions is better than indexOf( ) is more powerful. If it is an ordinary string or a specific string to be extracted, then using indexOf() is more efficient and saves resources. But if it is to find a special string, such as numbers and letters, Then indexOf() cannot be executed, and regular expressions and search() methods must be used.

 (5), match()

match(str/RegExp) Used to find the specified character in the string and return the character. This method cooperates with regular expressions The use effect is better. If you do not use a regular expression, it will only return the first occurrence of the specified character and will not match backwards. If it is matched with the regular expression and matches globally, all the specified characters in the string will be returned in the form of an array. If there is no If found, null is returned.

 (6), replace()

replace(str/RegExp, newstr) Used to replace some characters in a string with other characters and return a new string. This method has two parameters. The first parameter specifies the character that needs to be replaced. The second parameter is the new character, which is the character to be displayed after replacement. It works better when used with regular expressions and can replace all matches. The most common application is: sensitive word filtering.

 (7), lastIndexOf()

LastIndexOf() is the opposite of indexOf, lastIndexOf(a certain character, strat) Returns the last position of a character in the string starting from the specified position, Search from back to front at the specified position. The second parameter is optional, and its legal values ​​are 0 to the length of the string -1: str.length-1. If this parameter is not set, the search starts from the last character of the string. The return value is a numeric value. If it is found, it returns the last occurrence position of the character. If it is not found, it returns -1.

 (8), slice()

slice(start, end) Extract a certain part of the string and return the extracted part as a new string, excluding the end position character. The first parameter is the starting position, the position of the first character is 0, the second parameter end is optional, the subscript of the end position, if this parameter is not set, the extraction starts from the starting position to the last character of the string. A substring of characters. The parameter for extracting characters can be a negative number, which means counting from the end of the string, that is to say: -1 represents the last character of the string, -2 represents the second to last character, and so on. Extracting all characters can be written as: slice(0), or it can be used directly without setting parameters.

 (9), substr()

substr(start, length) Extract the characters of the specified string length from the beginning of the string, and return the extracted part as a new string. This method can be used instead of substring() and slice(). The first parameter is the starting position, which can be a negative number, then counting from the tail. The second parameter is the length of the extracted string. This parameter is optional and cannot be less than 1. Otherwise, an empty string is returned. If this parameter is not set, the substring from the starting position to the last character is returned.

 (10)、substring()

  substring(from, to)  提取介于字符串指定的两个下标中间的字符,并以新的字符串返回被提取的部分,不包括结束位置的字符。第一个参数规定提取子串的第一个字符在字符串中的位置,简单说就是开始位置,该参数是一个非负的整数。第二个参数是要提取的子串最后一个字符在字符串中的位置,也就是结束位置,该参数可选,为一个非负的整数,如果不设置该参数,则返回从开始位置到最后一个字符的子字符串。如果第二个参数比第一个参数大,则在提取子串之前会将较小的数作为开始位置,较大的作为结束位置。

  slice()、substr() 、substring()三者区别:

  从定义上看,三者都为提取子字符串,slice() 和substring() 可以看成是同类,参数都是字符串的某个开始位置到结束位置,都不包括结束位置。而 substr() 则是提取从字符串的某个位置开始,指定字符串长度的子字符串。他们的共同点都是:第二个参数可选,如果不设置,都返回从开始位置到最后一个字符的子字符串。

  从可设置的参数看,slice() 的两个参数都可为负数,表示从尾部开始算起。substr() 的第一个参数也可以设置为负数,而 substring() 的参数则不接受负数,如果设置为负数或者其他无效的数,则会被当作 0 处理。

  (11)、split()

  str.split()  用于分割字符串,返回字符串数组。该方法有2个可选的参数,第一个参数为分割方式,可以是正则表达式,第二个参数设置返回字符串的最大长度。

<script> var str = "Good good study day day up!"; 
 //忽略参数:
 var arr = str.split(); document.write(arr); //返回:Good good study day day up!
 
 //分割每个字符包括空格:
 var arr = str.split(&#39;&#39;); document.write(arr); //返回:G,o,o,d, ,g,o,o,d, ,s,t,u,d,y, ,d,a,y, ,d,a,y, ,u,p,!
 
 //使用空格作为分割符:
 var arr = str.split(&#39; &#39;); document.write(arr); //返回:Good,good,study,day,day,up!
 
 //规定返回数组的最大长度
 var arr = str.split(&#39; &#39;, 3); document.write(arr); //返回:Good,good,study
 
 //使用一个字符作为分割符:
 var arr = str.split(&#39;d&#39;); document.write(arr); //返回:Goo, goo, stu,y ,ay ,ay up!
 </script>
Copy after login

(12)、toString()

  toString()  方法用于将对象转换为字符串。

  (13)、valueOf()

  valueOf()  方法用于将对象转换为一个基本数据的值,返回对象的原始值。

  (14)、toLowerCase()

  str.toLowerCase()  方法用于将字符串转换为小写。

  (15)、toUpperCase()

  str.toUpperCase()  方法用于将字符串转换为大写。

2、Number 对象

  JS 只有一种数字类型,可以是整数,也可以是小数。整数最大可以有 15 位,小数最大可以有17位,在 JS 中小数运算并不是非常精确,所以大多数情况下,需要将小数转换为整数。注意:整数的第一位不能为 0,否则会得到意想不到的结果。如下面的运算结果:

var sum = 0.1 + 0.2; alert(sum); 
//返回:0.30000000000000004
Copy after login

(1)、infinity 和 -infinity

  当数字运算超过了 JS 所能表示的数字上限时,结果就为一个无穷大的值,在 JS 中用infinity表示。当负数运算超过了 JS 的负数范围,结果就为一个负无穷大的值,也叫无穷小,在 JS 中用 -infinity 表示。基于无穷大的加减乘数运算,他们的结果还是无穷大,并保留正负号。一个整数或者负数除以0,得到的都是无穷大。

  (2)、NaN

  NaN 表示非数字的特殊值,该属性用于指示一个值不是数字。返回值为布尔值。可以使用函数 isNaN() 判断一个值是否是 NaN 值。

var x = 123; var y = &#39;abc&#39;; 
 alert(isNaN(x));    //返回:false
 alert(isNaN(y));    //返回:ture
 
 alert(x == y);    //返回:false
 //NaN和NaN是不相等的。所以为假。
 
 var a = 2/0;
 alert(isNaN(a));    //返回:false
 //无穷大是一个数字
Copy after login

Number 对象属性:

  (1)、MAX_VALUE 和 MIN_VALUE

  MAX_VALUE 表示最大的数,它的近似值为: 1.7976931348623157 x 10308。如果大于该数则表示无穷大。MIN_VALUE 表示最小的数,它的近似值为:5 x 10-324,MIN_VALUE 是最接近 0 的数,但不是负值。比该属性小的值用 0 表示。由于他们都是 Number 对象的静态属性,只能通过 Number 调用,所以使用自定义的 Number 将无法获取属性,返回值为 undefined。

//JS最大数
 alert(Number.MAX_VALUE); //返回:1.7976931348623157e+308
 
 //JS最小数
 alert(Number.MIN_VALUE); //返回:5e-324
  
 //e为科学计数法:
 var a = 123e5; var b = 123e-5; 
 
 alert(a);    //返回:12300000
 alert(b);    //返回:0.00123
Copy after login

(2)、POSITIVE_INFINITY 和 NEGATIVE_INFINITY

  POSITIVE_INFINITY 属性代表无穷大,表示比 MAX_VALUE 大的数。NEGATIVE_INFINITY 属性表示负无穷大,表示比 MIN_VALUE 小的数。由于他们都是 Number 对象的静态属性,只能通过 Number 调用,所以使用自定义的 Number 将无法获取属性,返回值为 undefined。

alert(Number.POSITIVE_INFINITY); //返回:Infinity
 
 alert(Number.NEGATIVE_INFINITY); //返回:-Infinity
Copy after login

Number 对象方法:

  (1)、toExponential()

  toExponential(n)  可把对象的值转换成指数计数法。该方法有一个可选的参数,用于规定计数法中的小数位数,包括 0 和 20 之内的值,如果不设置该参数,将使用尽可能多的数字。

  (2)、toFixed()

  toFixed(n)  可把数字转换为字符串,并四舍五入为指定小数点后位数的数字。该方法必须设置一个参数,规定小数的位数,包括 0 和 20 之内的值,如果不设置该参数,将默认为 0。

  (3)、toPrecision()

  toPrecision(n)  可把数字格式化为指定的长度,如果超出指定的长度将转换为指数计数法。该方法必须设置一个参数,规定转换为指数计数法的最小位数,包括 1 和 21 之内的值,如果不设置该参数,则调用 toString() 方法,而不对数字转换。

  (4)、toString()

  toString()  方法用于将对象转换为字符串。

  (5)、valueOf()

  valueOf()  方法用于将对象转换为一个基本数据的值,返回对象的原始值。

3、Math 对象

  Math 对象的作用是:执行常见的算数任务。该对象无需在使用这个对象之前对它进行定义。

  下面主要介绍 Math 对象的一些常用方法:

  (1)、ceil()

  Math.ceil()  可对一个数向上取整,如果参数是一个整数,该值不变。向上取整运算返回的是一个大于或等于该值并且与之最接近的整数。

alert(Math.ceil(-0.1));    //返回:0
 
 alert(Math.ceil(-9.9));    //返回:-9
 
 alert(Math.ceil(2.1));     //返回:3
 
 alert(Math.ceil(2.9));     //返回:3
 
 var num = 8; alert(Math.ceil(num));    //返回:8
Copy after login

(2)、floor()

  Math.floor()  可对一个数进行向下取整,如果参数是一个整数,该值不变。向下取整运算返回一个小于或等于该值的最大整数。

alert(Math.floor(-0.1));    //返回:-1
 
 alert(Math.floor(-9.9));    //返回:-10
 
 alert(Math.floor(2.1));     //返回:2
 
 alert(Math.floor(2.9));     //返回:2
 
 var num = 8; alert(Math.floor(num));    //返回:8
Copy after login

(3)、round()

  Math.round()  可把一个数字四舍五入为最接近的整数。

alert(Math.round(-0.1));    //返回:0
 
 alert(Math.round(-9.9));    //返回:-10
 
 alert(Math.round(2.49));     //返回:2
 
 alert(Math.round(2.5));     //返回:3
 
 var num=8; alert(Math.round(num));    //返回:8
Copy after login

 (4)、random() 方法

  Math.random()  可返回介于 0 ~ 1(大于或等于 0 但小于 1 )之间的一个随机数。

 //获得一个随机数:
 alert(Math.random()); 
 //获得 0~10 之间的随机数:
 alert(Math.random()*10); 
 //random ()方法和round()方法配合,可获得一个不大于10的整数:
 alert(Math.round(Math.random()*10)); 
 //随机数每次返回的值都不同。
Copy after login

4、Array 对象

  数组对象的作用是:使用单个变量来存储一系列的值。

  数组最常用的属性就是 length,用于返回数组中数据的长度,也可用于设置数组的长度。

 var arr = [1,2,3,4,5,6]; arr.length=3; alert(arr);    //返回1,2,3
 
 //arr.length=0;        可用于快速清空数组
Copy after login

下面主要介绍 Array 对象一些常用方法:

  (1)、concat()

  arr.concat(arr1, arr2, ..., arrN)  用于连接两个或多个数组,该方法返回一个新数组,不改变原来数组。该方法的参数可以是具体的值,也可以是数组对象,可以是任意多个。如果该参数是具体的值,将把该值插入到原来的数组返回。

  (2)、join()

  join()  用于将数组中的所有元素转换成一个字符串,元素是通过指定的分隔符分隔的。该方法有一个可选参数,用于指定分隔方式。如果不设置该参数,默认使用逗号分割。

 var arr1 = [86,&#39;010&#39;] var arr2 = [15278654321] var arr3 = arr1.concat(arr2); 
 document.write(arr3.join()); //返回:86,010,15278654321
 
 document.write(arr3.join(".")); //返回:86.010.15278654321
 
 document.write(arr3.join("-")); //返回:86-010-15278654321
 
 document.write(arr3.join("|")); //返回:86|010|15278654321
Copy after login

(3)、reverse()

  arr.reverse()  用于颠倒数组中元素的顺序。

 var arr = [&#39;Banana&#39;, &#39;Orange&#39;, &#39;Apple&#39;]; document.write(arr); //返回:Banana, Orange, Apple
 
 document.write(arr.reverse()); //返回:Apple,Orange,Banana
Copy after login

(4)、slice()

  arr.slice(start, end)  可从已有的数组中返回选定的元素。该方法也适用于提取子字符串。也不包括开始位置和结束位置的元素。第一个参数规定从何处开始选取,第二个参数可选,规定从何处结束选取,如果省略该参数,则返回从开始位置到数组尾部的所有元素。如果参数为负数,则从数组最后一个元素开始算起。

  (5)、sort()

  arr.sort(方法函数)  用于对数组的元素排序。排序可以是字母或数字,并按升序或降序。默认排序顺序为按字母升序。使用数字排序,你必须通过一个函数作为参数来调用。函数指定数字是按照升序还是降序排列。如果数字排序不指定方法函数,默认是按照字母升序,则 100 会排在 15 前边。

var arr = [99,15,21,2,8,56,100,1]; 
 //默认排序:
 document.write(arr.sort()); //返回:1,100,15,2,21,56,8,99
 
 //指定方法函数,按升序排序。
 function ascNum(a,b) {     return a-b; } document.write(arr.sort(ascNum)); //返回:1,2,8,15,21,56,99,100
 
 //指定方法函数,按降序排序。
 function desNum(a,b) {     return b-a; } document.write(arr.sort(desNum)); //返回:100,99,56,21,15,8,2,1
Copy after login

(6)、shift()

  arr.shift()  删除数组的第一个元素。 此方法将改变数组的长度。

 var arr = [&#39;Banana&#39;, &#39;Orange&#39;, &#39;Apple&#39;]; document.write(arr.length);    //返回:3
 
 arr.shift(); document.write(arr);    //返回:Orange,Apple
 
 document.write(arr.length);     //返回:2
Copy after login

(7)、pop()

  arr.pop()  删除数组的最后一个元素。此方法将改变数组的长度。

var arr = [&#39;Banana&#39;, &#39;Orange&#39;, &#39;Apple&#39;]; document.write(arr.length);    //返回:3
 
 arr.pop(); document.write(arr);    //返回:Banana,Orange
 
 document.write(arr.length);     //返回:2
Copy after login

(8)、unshift()

  arr.unshift()  向数组开头添加一个或多个元素。此方法将改变数组的长度。

var arr = [&#39;Banana&#39;, &#39;Orange&#39;, &#39;Apple&#39;]; document.write(arr.length);    //返回:3
 
 arr.unshift(&#39;Mango&#39;, &#39;Pear&#39;); document.write(arr); //返回:Mango,Pear,Banana,Orange,Apple
 
 document.write(arr.length);    //返回:5
Copy after login

(9)、push()

  arr.push()  向数组末尾添加一个或多个元素。此方法将该变数组的长度。

 var arr= [&#39;Banana&#39;, &#39;Orange&#39;, &#39;Apple&#39;]; document.write(arr.length);    //返回:3
 
 arr.push(&#39;Mango&#39;, &#39;Pear&#39;,&#39;Lemon&#39;); document.write(arr); //返回:Banana,Orange,Apple,Mango,Pear,Lemon
 
 document.write(arr.length);    //返回:6
Copy after login

(10)、splice()

  arr.splice(start, length, arrElement1, ..., arrElementN)  用于删除、插入或替换数组的元素。该方法会改变数组的原始数据。该方法有多个参数,前两个为必须的参数。第一个参数规定从何处开始删除或插入。第二个参数规定删除元素的长度,如果设置为 0,则不删除元素,如果不定义该参数,则删除从 start 规定的位置开始到原数组结尾的所有元素。最后的参数可选,要添加到数组的新元素。

 var arr = [1,2,3,4,5,6]; 
 //删除元素的应用:
 //从第2个位置开始,删除长度为3。
 arr.splice(2,3); document.write(arr+&#39;<br>&#39;); //返回:1,2,6
 
 //插入元素的应用:
 //从第2个位置开始,删除为0个元素,也就是不删除,插入abc。
 arr.splice(2,0,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;); document.write(arr+&#39;<br>&#39;); //返回:1,2,a,b,c,3,4,5,6
 
 //替换元素的应用:
 //从第2个位置开始,删除3个元素,再插入def。
 arr.splice(2,3,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;); document.write(arr); //返回:1,2,d,e,f,6
Copy after login

(11)、toString()

  toString()  方法可把数组转换为字符串,并返回结果。

  (12)、valueOf()

  valueOf()  方法返回数组对象的原始值。

5、Date 对象

  Date 对象用于处理日期和时间。可以通过 new 关键词来定义 Date 对象。

  下面例子是获取当前的所有日期:

 var d = new Date(); //获取当前日期
 document.write(d);  
 //获取当前的年份
 document.write(d.getFullYear() + &#39;年&#39;); 
 //获取当前月份,月份从0开始计算,所以需要+1
 document.write(d.getMonth() + 1 + &#39;月&#39;); 
 //获取当前是当月中的哪一天
 document.write(d.getDate() + &#39;日&#39;); 
 //获取当前时间的小时
 document.write(d.getHours() + &#39;时&#39;); 
 //获取当前时间的分钟
 document.write(d.getMinutes() + &#39;分&#39;); 
 //获取当前时的秒数
 document.write(d.getSeconds() + &#39;秒&#39;); 
 //获取当前的毫秒数t
 document.write(d.getMilliseconds() + &#39;毫秒&#39;); 
 //获取星期
 document.write(&#39;星期&#39; + d.getDay()); 
 //星期从0开始算起,从星期天开始计算。
 //getDay()返回的是0-6的数字,0表示星期天。如果要返回相对应的“星期”,需要通过数组完成。
 var weekday = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; var week = d.getDay(); document.write(weekday[week]);
Copy after login

  下面例子用于设置日期:

var d = new Date(); 
 //设置年份
 d.setFullYear(2020); document.write(d); 
 //该方法也可用于设置月份(介于0-11之间)和天数(介于1-31之间)。
 //月份:-1为去年的最后一月,-2为去年的倒数第二个月。
 //12为明年的第一个月,13为明年的第二个月。
 //天数:0为上个月最后一天,-1为上个月最后一天之前的天数。
 //如果当月有31天,32为下个月第一天,如果当天只有30天,32则为下个月的第二天
 d.setFullYear(2020, 11, -1); document.write(d); //设置月份(介于0-11之间),也可用于设置天数
 d.setMonth(5); document.write(d); 
 
 //设置天数(介于1-31之间)
 d.setDate(12); document.write(d); 
 //设置小时
 //值介于0(午夜)-23(晚上11点)之间,-1为昨天的最后一个小时,24为明天的第一个小时
 d.setHours(24); document.write(d); 
 //该方法也可用于设置分钟、秒以及毫秒数。
 //分钟:介于0-59之间,-1为上一小时最后一分钟,60为下一个小时第一分钟
 //秒:介于0-59之间,-1为上一分钟最后一秒,60为下一分钟第一秒
 //毫秒:介于0-999之间,-1为上一秒钟的最后一毫秒,1000为下一秒钟的第一毫秒
 d.setHours(21,30,1); document.write(d); 
 //获取小时 一个小应用:返回24小时之前的的时间
 var d = new Date(); d.setHours(d.getHours()-24); document.write(d); 
 //设置分钟,也可用于设置秒数和毫秒数
 d.setMinutes(20); document.write(d); 
 //设置秒,也可用于设置毫秒
 d.setSeconds(10); document.write(d); 
 //设置毫秒
 d.setMilliseconds(999); document.write(d);
Copy after login

  getTime() 和 setTime()

var d = new Date(); 
 //获取1970年元旦距今的毫秒数
 document.write(d.getTime()+&#39;毫秒&#39;); 
 //向1970年元旦增加1325347200000毫秒,返回新日期
 d.setTime(1325347200000); document.write(d); 
 //获取指定时间据1970年之间的毫秒数
 var d = Date.parse("2012, 12, 12"); document.write(d+&#39;毫秒&#39;); 
 //计算1970年元旦至今有多少年:
 var minutes = 1000*60; var hours = minutes*60; var day = hours*24; var year = day*365; var d = new Date(); var t = d.getTime(); var y = Math.round(t/year);
 document.write(y + &#39;年&#39;);
Copy after login

  日期转换:

var d = new Date(); //当前时间
 document.write(d); 
 //将日期部分(不包括时分秒)转换为字符串
 document.write(d.toDateString()); 
 //将日期部分(不包括年月日)转换为字符串
 document.write(d.toTimeString()); 
 //根据本地时间将日期转换为字符串
 document.write(d.toLocaleString()); 
 //根据本地时间将日期部分(不包括时分秒)转换为字符串
 document.write(d.toLocaleDateString()); 
 //根据本地时间将日期部分(不包括年月日)转换为字符串
 document.write(d.toLocaleTimeString()); 
 //使用ISO标准将日期转换为字符串
 //该标准格式为:YYYY-MM-DDTHH:mm:ss.sssZ
 document.write(d.toISOString()); 
 //将日期转换为JSON格式
 //JSON格式与ISO标准是同样的格式
 document.write(d.toJSON());
Copy after login

toString()  方法可把日期对象转换为字符串,当日期需要显示为一个字符串时,该方法会被自动调用。

  valueOf()  方法返回日期对象的原始值。该方法将返回1970年元旦至今的毫秒数。

6、数据类型转换

  JS 中有5种不同的数据类型:string、number、boolean、object、function。

  3 种对象类型:Object、Date、Array。2 个不包含任何值的类型:ubll、undefined。

  可以使用 typeof 操作符来查看 JS 变量的数据类型。

 var str = &#39;小明&#39;; alert(typeof str);    //返回:string
 
 var num = 12; alert(typeof num);    //返回:number
 
 var num1 = NaN; alert(typeof num1);    //返回:number
 
 var fun = function (){alert(&#39;abcd&#39;);}; alert(typeof fun);    //返回:function
 
 var boo = true; alert(typeof boo);    //返回:boolean
 
 var obj = document; alert(typeof obj);    //返回:object
 
 var arr = [1,2,3,4]; alert(typeof arr);    //返回:object
 
 var d = new Date(); alert(typeof d);    //返回:object
 
 var json = {a:&#39;12&#39;, b:21}; alert(typeof json);    //返回:object
 
 var n = null; alert(typeof n);    //返回:object
 
 var x; alert(typeof x);        //返回:undefined
 alert(typeof y);        //返回:undefined
 //未定义有2种情况:
 //1、真的没有定义(如y)
 //2、虽然定义了,但是没有给赋值(如x)
Copy after login

数组对象和日期对象无法通过 typeof 来判断数据类型,因为都返回 object。可以使用 constructor 属性来查看。constructor 属性返回一个对象的构造函数,将返回的构造函数转换为字符串,再判断是否包含数组和日期。

 //返回数组和日期的构造函数:
 var arr = ["abc", "123", "123abc", "abc123"]; alert(arr.constructor); //返回:function Array() { [native code] }
 
 var d = new Date; alert(d.constructor); //返回:function Date() { [native code] }
 
 
 var arr = ["abc", "123", "123abc", "abc123"]; function con(obj) {     return arr.constructor.toString().indexOf("Array") > -1; } alert(con(arr));    //返回:ture
 
 var d = new Date(); function cons(obj) {     return d.constructor.toString().indexOf("Date") > -1; } alert(cons(d));    //返回:ture
Copy after login

强制类型转换,也叫显式类型转换。

  (1)、转换为字符串:

  全局方法 string() 和 toString() 方法可用于将一个值转换为字符串。string() 可用于任何类型的数字、字母、变量、表达式。

  二者区别:

  大多数值都有 toString() 方法,除了 null 和 undefined。字符串本身也可以使用 toString() 方法,将返回字符串的原始值。

  任何值都可以使用 string() 方法,如果该值有 toString() 方法,则使用该方法,如果该值没有 toString() 方法,那就为 null 和 undefined,则返回 null 和 undefined。

var str = &#39;小明&#39;; alert(String(str)); alert(str.toString()); //都返回:小明
 
 var num = 123; alert(String(num)); alert(num.toString()); //都返回:123
 
 var and = 123+100; alert(String(and)); alert(and.toString()); //都返回:223
Copy after login

(2)、转换为数字:

  全局方法 Number() 可以将字符串转换为数字。空字符串转换为 0,特殊值字符串将转换为 NaN。

var str = &#39;123&#39;; alert(Number(str));    //返回:123
 
 var str = &#39;&#39;; alert(Number(str));    //返回:0
 
 var str = &#39;200px&#39;; alert(Number(str));    //返回:NaN
Copy after login

  最常用的就是转换为整数和小数。parseInt() 方法用于转换整数。parseFloat() 方法用于转换小数。

 var a = &#39;3.1&#39;
 alert(parseInt(a));    //返回:3
 var a = &#39;3.9&#39;
 alert(parseInt(a));    //返回:3
 var a = &#39;12px34&#39;; alert(parseInt(a));    //返回:12
 var a = &#39;px1234&#39;; alert(parseInt(a));    //返回:NaN
 
 var d = &#39;3.14&#39;; alert(parseFloat(d));    //返回:3.14
 var d = &#39;3.99&#39;; alert(parseFloat(d));    //返回:3.99
Copy after login

  + 运算符可以连接字符串,也可以将字符串转换为数字。

var n = &#39;12ab&#39;; var x = &#39;34&#39;; alert(n+x);    //返回:12ab34
 alert(parseInt(n)+x);    //返回:1234
 
 var y = + x; alert(typeof x);    //返回:string
 //若变量不能转换,但仍然是一个数字,NaN
 alert(typeof y);    //返回:number
Copy after login

  NaN 的数据类型是 number,NaN 表示非数字(Not a Number),所以本身也为数字。

var a = parseInt(&#39;abc&#39;); var b = parseInt(&#39;12edf&#39;); var c = 12+NaN; alert(c);    //返回NaN
 
 //判断NaN是否等于NaN
 alert(a==b);    //返回false
 
 //isNaN判断一个变量是不是NaN
 alert(isNaN(a));    //返回:true
 alert(isNaN(b));    //返回:flase
Copy after login

  利用这一特性,可以做一个简易的文本框求和,用户输入的文本框的值为字符串,需要将字符串转换为数字,再判断输入的值是否为数字。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>文本框求和</title>
 </head>
 <script>
 window.onload = function (){     
 var x = document.getElementById(&#39;txt1&#39;);     
 var y = document.getElementById(&#39;txt2&#39;);    
  var oBth = document.getElementById(&#39;but1&#39;);     
  oBth.onclick = function (){         
  //将输入的值转换为整数:
         var n1 = parseInt(x.value);         
         var n2 = parseInt(y.value);             
         //判断用户输入的n1是不是非数字
             if(isNaN(n1)){                 
             alert(&#39;输入的第一个数字有误&#39;);             
             }             
             else if(isNaN(n2)){                 
             alert(&#39;输入的第二个数字有误&#39;);             
             }             
             //若都输入的为数字,则求和
             else{                 
             alert(n1+n2);             
             }     
             };
              }; 
              </script>
 <body>
 <input id="txt1" type="text" >
 <input id="txt2" type="text" >
 <input id="but1" type="button" value="求和">
 </body>
 </html>
Copy after login

  全局方法 Number() 可将布尔值转换为数字。

alert(Number(false));    //返回 0
 alert(Number(true));    // 返回 1
Copy after login

隐式类型转换,也叫自动转换类型。

  当 JS 尝试操作一个“错误”的数据类型时,会自动转换为“正确”的类型再去执行,这就是隐式类型转换。直接看几个例子:

var a = 2; var b = &#39;2&#39;; //比较数字2和字符串2是否相等
 alert(a==b);    //返回:true
 //why? 相等比较实际上比较前是先将a和b转换为同一类型,再进行比较的。
 
 //比较数字2和字符串2是否全等
 alert(a===b);    //返回:返回false
 //why? 全等比较不转换类型,直接比较。a为数字,b为字符串。
 //所以,一般情况下,采用全等比较,更为严谨。
 
 var c = &#39;12&#39;; var d = &#39;5&#39;; //两个值为数字的字符串做+运算
 alert(c+d);    //返回125
 //why? "+"运算符有2种功能:1、字符串连接。2、算术运算(数字相加)。系统会采用最直接的方法。
 
 //两个值为数字的字符串做-运算
 alert(c-d);  //返回7
 //why? 在做减法运算时会先转换为同类型,再做运算。"-"运算符只有1种功能。算术运算(数字相减)。
Copy after login

以上就是 JavaScript学习总结【3】JS对象的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!