前端三劍客——javascript內置對象與其方法
大綱:
??1.對象創建的常用3種方法
????? 引用/新增屬性方法
??2.內置對象及其常見方法
??????Number
??????Math
??????Date
??????String
??????Array
??????對象與數組的解包操作以及在函數中的運用
??????JSON
??????console
對象創建的方法
??對象創建的常用三種方法
//方法一 直接創建有屬性和方法的對象
var Person={
name:"guohan",
age:22,
say(){
console.log(Person.name);
}
}
//引用屬性和方法
console.log(Person.name);
Person.say();
//新增屬性和方法
Person["hobby1"]="睡覺";
Person.hobby2="打球";
Person.call=function(){
console.log(this.hobby1); //如果是箭頭函數則this指向父級作用域的this是window
}
Person.call();
//方法二創建函數后實例對象
function Person(name,age){
this.name=name;
this.age=age;
this.say=()=>{
console.log(this.age);
}
}
//實例化對象和引用屬性和方法
var man = new Person("guohan",22);
console.log(man.name);
man.say();
//新增屬性和方法
man.call=function (){
console.log(man.age);
}
man.call();
//方法三創建類后實例類的對象
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
say(){
console.log(this.age);
}
}
//實例化對象和引用屬性和方法
var man = new Person("guohan",22);
console.log(man.name);
man.say();
//新增屬性和方法
man.call=function(){
console.log(man.age);
}
man.call();
內置對象及其方法

??Number??數值對象
toFixed(n ):保留n個小數位
var num = 3.14;
console.log(num.toFixed()); //3
console.log(num.toFixed(1)); //3.1
console.log(num.toFixed(3)); //3.140
??Math????數學對象
Math.round(num) 對num進行四舍五入!取整!
//Math.round(num) 對num進行四舍五入!取整!
console.log(Math.round(3.145)); //3
//與python區別
/**
* num = 10.346
* print(round(num,2)) //10.35
*/
Math.ceil(nun) 對num進行向上取整 進一法取整
//Math.ceil(nun) 對num進行向上取整 進一法取整
console.log(Math.ceil(2.1)); //3
Math.floor(num) 向下取整:保留整數部分去除小數部分
//Math.floor(num) 向下取整:保留整數部分去除小數部分
console.log(Math.floor(3.64)); //3
Math.random() 獲取[0,1)之間的隨機數
//Math.random() 獲取[0,1)之間的隨機數
console.log(Math.random().toFixed(2)); //0.36
//Math.random()*100 獲取[0,100)之間的隨機數
console.log((Math.random()*100).toFixed(2)); //45.84
//parseInt(Math.random()*100) 獲取[0,100)之間的隨機數整數
console.log(parseInt((Math.random() * 100).toFixed(2))); //26
//隨機返回指定范圍的整數
var ret = (min,max)=>parseInt(Math.random()*(max-min))+min;
/*
function ret(min,max){
return parseInt(Math.random()*(max-min))+min;
}
*/
console.log(ret(20,40));
??Date????時間對象
/**
* 創建Date時間對象: var t = new Date();
* 獲取系統本地時間: console.log(t);
* 獲取年份: t.getFullYear();
* 獲取月份(0-11): t.getMonth()+1;
* 獲取幾號(1-31): t.getDate();
* 獲取星期幾(0-6): t.getDay();
* 獲取小時: t.getHours();
* 獲取分鐘: t.getMinutes();
* 獲取秒數: t.getSeconds();
* 獲取時間戳: t.getTime();
* 獲取JSON格式時間: t.toJSON();
* @type {Date}
*/
//Date時間對象及其方法
/**
* 創建Date時間對象: var t = new Date();
* 獲取系統本地時間: console.log(t);
* 獲取年份: t.getFullYear();
* 獲取月份(0-11): t.getMonth()+1;
* 獲取幾號(1-31): t.getDate();
* 獲取星期幾(0-6): t.getDay();
* 獲取小時: t.getHours();
* 獲取分鐘: t.getMinutes();
* 獲取秒數: t.getSeconds();
* 獲取時間戳: t.getTime();
* 獲取JSON格式時間: t.toJSON();
* @type {Date}
*/
var t = new Date();
//實例化時間對象new Date(): 獲取系統本地時間
console.log(t); //Sun Nov 02 2025 21:37:22 GMT+0800 (中國標準時間)
//對象.getFullYear(): 獲取年份
console.log(t.getFullYear()); //2025
//對象.getMonth(): 獲取月份(0-11) 0:11月 要加一
console.log(t.getMonth()+1);
//對象.getDate(): 獲取幾號(1-31)
console.log(t.getDate()); //2
//對象.getDay(): 獲取星期幾(0-6) 0:星期天
console.log(t.getDay()); //0
//對象.getHours(): 獲取小時
console.log(t.getHours()); //22
//對象.getMinutes(): 獲取分鐘
console.log(t.getMinutes()); //6
//對象.getSeconds(): 獲取秒
console.log(t.getSeconds()); //40
//獲取時間戳1970-1-1
console.log(t.getTime()); //1762092410769
//對象.toJSON(): 以JSON數據格式返回時間字符串
console.log(t.toJSON(),typeof t.toJSON() ); //2025-11-02T14:10:53.322Z string
//補0:比如分鐘為10以內時顯示:08
// function cramZero(param){
// if(String(param).length<2){
// param = '0'+param;
// return param;
// }
// return param;
// }
var cramZero = (param) => String(param).length<2?'0'+param:param;
ret = `${t.getFullYear()}-${cramZero(t.getMonth()+1)}-${cramZero(t.getDate())}-${cramZero(t.getHours())}-${cramZero(t.getMinutes())}-${cramZero(t.getSeconds())}`;
console.log(ret);
??String????字符串對象
//String字符串對象及其方法
/**
* var s = "guohan";
* 拼接2個或者多個字符: s.concat(str);
*將Unicode編碼值轉成對應字符: s.fromCharCode(num)
*返回指定字符首次的索引位置: s.indexOf()
* 判斷是否以某個字符開頭結尾: s.startsWith/endsWith()
* 判斷是否包含某字符串: s.includes()
* 獲取字符串切片(支持負數索引): s.slice(start,end)
* 獲取字符串切片: s.subString(start,end)
* 獲取指定長度字符串切片: s.str(start,len)
*變大寫/小寫: s.toUpperCase/toLowerCase()
* 去空白: s.trim()
*分割: s.split(指定字符)
*替換一次/全部替換: s.replace/replaceAll()
*search()
*match()
* @type {string}
*/
//String字符串對象及其方法
/**
* var s = "guohan";
* 拼接2個或者多個字符: s.concat(str);
*將Unicode編碼值轉成對應字符: s.fromCharCode(num)
*返回指定字符首次的索引位置: s.indexOf()
* 判斷是否以某個字符開頭結尾: s.startsWith/endsWith()
* 判斷是否包含某字符串: s.includes()
* 獲取字符串切片(支持負數索引): s.slice(start,end)
* 獲取字符串切片: s.subString(start,end)
* 獲取指定長度字符串切片: s.str(start,len)
*變大寫/小寫: s.toUpperCase/toLowerCase()
* 去空白: s.trim()
*分割: s.split(指定字符)
*替換一次/全部替換: s.replace/replaceAll()
*search()
*match()
* @type {string}
*/
var s = "guo";
//對象.concat(字符串): 字符串拼接拼接2個或更多個
console.log(s.concat("han")); //guohan
//對象.fromCharCode(): 將一個或者多個Unicode編碼值裝換成對應的字符 相當于py中chr
//py: print(chr(65))
console.log(String.fromCharCode(65)); //A
//對象.indexOf(字符): 返回指定的字符在字符串中首次出現的位置
console.log(s.indexOf('o')); //2
//對象.startsWith(字符): 判斷是否以某個字符開頭
console.log(s.startsWith('s')); //false
//對象.endsWith(字符): 判斷是否以某個字符結束
console.log(s.endsWith('o')); //true
//對象.includes(字符): 判斷是否包含某個字符串
console.log(s.includes('uo')); //true
//對象.slice(開始下標,結束下標): [start,end) 獲取指定位置的切片支持負數索引
console.log(s.slice(0, -1)); //gu
//對象.subString(開始下標,結束下標): [start,end) 獲取指定位置的切片
console.log(s.substring(0, 2)); //gu
//對象.substr(開始下標,截取長度): [start,len] 獲取從指定索引位置獲取指定數目的字符
console.log(s.substr(0, 2)); //gu
//對象.toUpperCase(): 將字符串變成大寫
console.log(s.toUpperCase()); //GUO
//對象.toLowerCase(): 將字符串變成小寫
console.log(s.toLowerCase()); //guo
///對象.trim(): 去除字符串兩邊空白
console.log(s.trim());
//以指定字符分割成數組
console.log(s.split("")); //['g', 'u', 'o']
//替換一次
console.log(s.replace("g", "h")); //huo
//py:默認全部替換,后加次數可指定替換次數
//全部替換
console.log(s.replaceAll("g", "h"));
//search()
//match()
???RegExp
????
????待補
??Array????數組對象
//Array
/**
* var num=["guohan","gh","gg","hh"]
* 增刪改查
* 增:
* 頭部增加: array.unshift(value)
* 尾部增加: array.push(value)
* 指定位置增加: array.splice(index,0,value)
*
* 刪:
* 頭部刪除: array.shift()
* 尾部刪除: array.pop()
* 指定位置刪除: array.splice(index,number)
*
* 改: array.splice(index,1,value)
*
* 查:
* 下標
* 查某個成員下標: array.indexOf(value)
* 循環數組成員下標: for(var index in array){console.log(index)}
* 值
* 查指定索引位置元素: array[index]
* 切片(左閉右開)支持負索引: array.slice(star,end)
* 循環數組所有成員: for(var value of array){console.log(value)}
* forEach函數查數組成員/下標: array.forEach((value,index,array)=>{console.log(value,index,array})
* 判斷
* 判斷指定元素是否包含于數組: array.includes(value)
* 判斷指定元素是否是數組: Array.isArray(value)
* 判斷數組成員是否均滿足條件: array.every(func)
* 判斷數組成員是否至少有一個滿足條件: array,some(func)
*
*
* 順序相關
* 反轉: array.reverse()
* 按ascii碼值進行排序: array.sort()
*
* 拼接
* 數組拼接: array.concat(new_array)
* 數組按指定字符拼接成字符串: array.join(str)
*
* 高級函數方法對數組進行操作
* 通過指定函數對數組每個成員進行處理: array.map(函數)
* 通過指定函數對數組每個成員進行篩選: array.filter(函數)
* 通過指定函數對數組成員進行累計: array.reduce(函數)
*
*
* @type {string[]}
*/
//Array
/**
* var num=["guohan","gh","gg","hh"]
* 增刪改查
* 增:
* 頭部增加: array.unshift(value)
* 尾部增加: array.push(value)
* 指定位置增加: array.splice(index,0,value)
*
* 刪:
* 頭部刪除: array.shift()
* 尾部刪除: array.pop()
* 指定位置刪除: array.splice(index,number)
*
* 改: array.splice(index,1,value)
*
* 查:
* 下標
* 查某個成員下標: array.indexOf(value)
* 循環數組成員下標: for(var index in array){console.log(index)}
* 值
* 查指定索引位置元素: array[index]
* 切片(左閉右開)支持負索引: array.slice(star,end)
* 循環數組所有成員: for(var value of array){console.log(value)}
* forEach函數查數組成員/下標: array.forEach((value,index,array)=>{console.log(value,index,array})
* 判斷
* 判斷指定元素是否包含于數組: array.includes(value)
* 判斷指定元素是否是數組: Array.isArray(value)
* 判斷數組成員是否均滿足條件: array.every(func)
* 判斷數組成員是否至少有一個滿足條件: array,some(func)
*
*
* 順序相關
* 反轉: array.reverse()
* 按ascii碼值進行排序: array.sort()
*
* 拼接
* 數組拼接: array.concat(new_array)
* 數組按指定字符拼接成字符串: array.join(str)
*
* 高級函數方法對數組進行操作
* 通過指定函數對數組每個成員進行處理: array.map(函數)
* 通過指定函數對數組每個成員進行篩選: array.filter(函數)
* 通過指定函數對數組成員進行累計: array.reduce(函數)
*
*
* @type {string[]}
*/
var num=["guohan","gh","gg","hh"];
//對象.concat(數組)
console.log(num.concat([1, 2, 3]),num.concat([1, 2, 3]).length); //['guohan', 'gh', 'gg', 'hh', 1, 2, 3]
//增加
//對象.push(): 尾部增加
num.push("h")
console.log(num); //['guohan', 'gh', 'gg', 'hh', 'h']
//對象.unshift(): 頭部增加
num.unshift("h");
console.log(num); //['h', 'guohan', 'gh', 'gg', 'hh', 'h']
//刪除
//對象.pop(): 尾部刪除
num.pop();
console.log(num); //['h', 'guohan', 'gh', 'gg', 'hh']
//對象.shift(): 頭部刪除
num.shift();
console.log(num); //['guohan', 'gh', 'gg', 'hh']
//指定位置增加刪除和修改
//對象.splice(索引,刪除的元素個數,增加的元素1,增加的元素2)
//刪除
console.log(num.splice(1, 2)); //['gh', 'gg']
console.log(num); //['guohan', 'hh']
//增加
num.splice(1,0,222,333);
console.log(num,num.length); //['guohan', 222, 333, 'hh'] 4
//修改
num.splice(1,1,"gh");
console.log(num); //['guohan', 'gh', 333, 'hh']
//指定數組成員返回索引
console.log(num.indexOf("guohan")); //0
//判斷指定成員是否在數組中
console.log(num.includes("guohan")); //true
//對象.slice(start,end): 反回數組切片左閉右開
console.log(num.slice(1,-1)); //[222, 333]
//對數組進行循環操作
//for循環獲取下標
for(var data in num){
console.log(data);
}
//for循環獲取成員
for(var data of num){
console.log(data);
}
//對象.forEach((值,索引,數組本身)=>{代碼})
num.forEach((value,index,array)=>{
console.log(value,index,array);
})
//反轉數組順序
num.reverse();
console.log(num); //['hh', 333, 'gh', 'guohan']
//對象.sort(): 根據ascii碼值進行排序
console.log(num.sort());
//以指定字符對數組進行拼接得到字符串
console.log(num.join("")); //333ghguohanhh
//案例:對字符串進行反轉
function strrev(str){
ret = str.split("").reverse().join("")
return ret;
}
console.log(strrev("guohan")); //333ghguohanhh
//Array.isArray(對象): 判斷指定對象是不是數組
console.log(Array.isArray(num)); //true
//[333, 'gh', 'guohan', 'hh']
//高級方法
//對象.map(指定函數): 通過指定函數對數組每個成員進行處理
console.log(num.map((value) => typeof (value) === 'number' ? value + 1 : value)); //[334, 'gh', 'guohan', 'hh']
console.log(num.map(function (value) {
if (typeof (value) === 'number') {
return value += 1;
}else{
return value;
}
})); //[334, 'gh', 'guohan', 'hh']
//對象.filter(篩選函數): 通過指定函數對數組成員進行篩選
console.log(num.filter((value) => typeof (value) === 'string' ? value : null)); //['gh', 'guohan', 'hh']
console.log(num.filter((value) => typeof (value) === 'number' ? value : null)); //333]
console.log(num.filter(function (value) {
if (typeof (value) === 'number') {
return value;
} else {
return null;
}
})); //333]
//對象.reduce(函數(參數1,參數2)): 通過指定函數對數組成員進行累計操作
console.log(num.reduce((value1, value2) => {
return value1 + value2;
})); //333ghguohanhh
/**
* python中內置函數
* import functools
* content = [1,22,44,"gouhan","gh"]
*
* #內置函數map
* result1 = list(map(lambda x:x+2 if isinstance(x,int) else x,content))
* print(result1) [3, 24, 46, 'gouhan', 'gh']
*
* #內置函數filter
* result2 = list(filter(lambda x: isinstance(x,int),content))
* print(result2) [1, 22, 44]
*
* #內置函數reduce
* result3 = functools.reduce(lambda x,y:x+y if isinstance(x and y,int) else str(x)+y,content)
* print(result3) 67gouhangh
*/
//[333, 'gh', 'guohan', 'hh']
//對象.every(函數): 判斷數組成員是否均滿足條件,
console.log(num.every((value) => {
return typeof value === 'string';
})); //false
//判斷數組成員是否至少有一個滿足條件
console.log(num.some((value) => {
return typeof value === 'string';
})); //true
??對象與數組的解包操作以及在函數中的運用????
??????數組解包
//數組解包
var array = [1,2,3,4];
//全接受
var [num1,num2,num3,num4] = array;
console.log(num1,num2,num3,num4); //1 2 3 4
//順序接收:部分接收
var [number1, ,number2] = array;
console.log(number1,number2); //1 3
//順序接收:接收剩余數據
var [data1,data2,...args] = array;
console.log(args); //[3, 4]
??????對象解包
//對象解包
//不需要按順序接收,而是按屬性值接收,且屬性名可以重新進行命名,不存在的屬性值可以指定默認值,不指定則為undefined
var Person = {name:"guohan",age:22,city:"hubei"};
//不存在的屬性指定默認值
var {name,city,age,phone="111",hobby}=Person;
console.log(name,age,phone,hobby); //guohan 22 111 undefined
//屬性名重新命名
var {name : myName,age : myAge}=Person;
console.log(myName,myAge,phone,hobby); //guohan 22 111 undefined
??????解包在函數中的運用
//解包在函數中的運用
//對象解包
function func1({x,y}){
console.log(x+y);
}
func1({x:10,y:20}); //30
//數組解包
function func2([x,y]){
console.log(x,y);
}
func2([1,2]); //1 2
function func3([x,...args]){
console.log(args);
}
func3([1,2,3,4]); //[2, 3, 4]
??JSON
//JSON
/**
* JSON.stringify(obj): 把js對象轉成JSON格式的字符串
* JSON.parse(str): 把JSON格式的字符串轉成js對象
* @type {{name: string, age: number}}
*/
//JSON
/**
* JSON.stringify(obj): 把js對象轉成JSON格式的字符串
* JSON.parse(str): 把JSON格式的字符串轉成js對象
* @type {{name: string, age: number}}
*/
//JSON.stringify(obj): 把對象轉成JSON格式的字符串
var obj = {name:"gh",age:22};
console.log(JSON.stringify(obj)); //{"name":"gh","age":22}
//JSON.parse(str): 把符合JSON語法的字符串轉換成js對象
var obj2 = '{"name":"gh","age":22}';
console.log(JSON.parse(obj2)); //Object: {name: 'gh', age: 22}
//與python區別
/*
"""
#import json
#json.dumps(obj): 把python中對象轉成JSON格式字符串
#jspn.dumps(obj,ensure_ascii=False): 對象中有中文時序列化
#json.loads(str): 把json格式字符串轉成python對象
python中set datetime類型不可以轉成json格式的字符串
python中元組序列化轉成[] 反序列化時得到列表
"""
import json
info = {'name':'guohan','age':22}
#把python中對象轉成json格式字符串
print(json.dumps(info)) #{"name": "guohan", "age": 22}
#python對象中有中文時序列化
info = {'name':'郭晗','age':22}
print(json.dumps(info,ensure_ascii=False)) #{"name": "郭晗", "age": 22}
#把json格式字符串轉成python對象
content = '{"name": "guohan", "age": 22}'
print(json.loads(content)) #{'name': 'guohan', 'age': 22}
content2 = '{"name": "郭晗", "age": 22}'
print(json.loads(content2)) #{'name': '郭晗', 'age': 22}
#集合無法序列化
info3 = {'guohan',22}
try:
print(json.dumps(info3))
except TypeError as e:
print("無法序列化") #無法序列化
#元組序列化和反序列化
data = (1,2,3)
print(json.dumps(data)) #[1, 2, 3]
data2 = '[1, 2, 3]'
print(json.loads(data2)) #[1, 2, 3]
*/
??console????控制臺操作對象,瀏覽器中進行代碼打印與調試
//console.dir(): 打印HTML元素變量信息
console.dir(document.body);
//console.table(): 以表格形式打印數組對象信息
var info = {name:"guohan",age:22};
console.table(info);
浙公網安備 33010602011771號