JavaScript引用类型核心操作方法详解

作者:青柠时间:2026-10-30 06:06:57浏览:457

本文系统梳理JavaScript中Object、Array、Date、RegExp、Function及String等引用类型的核心操作方法。涵盖数组的排序、切片与拼接,正则表达式的构建与匹配,函数作用域与调用机制,以及字符串的编码与截取技巧,帮助开发者掌握常用内置对象的使用规范。

Object与Array类型操作

Object类型

Array类型包含重排序方法,其中compare函数用于定义排序逻辑。


function compare(value1, value2){
  if (value1<value2){
    return -1;
  }
  if (value1>value2){
    return 1;
  } else{
    return 0;
  }
}
var values = [0,1,5,10,15];
values.sort(compare);
console.log(values); // [0,1,5,10,15]

升序排列的实现方式如下:


function compare(value1, value2){
  if (value1<value2){
    return 1;
  }
  if (value1>value2){
    return -1;
  } else{
    return 0;
  }
}

slice(start, end)方法用于截取数组。该方法返回从指定起始位置到数组末尾的所有元素;若提供两个参数,则返回起始位置与结束位置之间的元素,但不包含结束位置对应的元素。


var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);

console.log(colors2); // green, blue, yellow, purple
console.log(colors3); // green, blue, yellow

splice()方法具备删除、插入和替换数组元素的功能。

执行删除操作时,需要指定两个参数:要删除的第一个元素的索引位置,以及要删除的元素数量。


var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1);
console.log(colors); // greeen, blue
console.log(removed); // red

执行插入操作时,需要三个参数:起始插入位置、0(表示不删除任何元素)以及要插入的一个或多个新元素。


var colors = ["red", "green", "blue"];
var removed = colors.splice(1,0,"yellow", "orange");
console.log(colors); // ["red", "yellow", "orange", "green", "blue"]
console.log(removed); // 返回空

执行替换操作时,需要三个参数:起始位置、要删除的元素数量,以及要插入的任意数量的新元素。


var colors = ["red", "green", "blue"];
var removed = colors.splice(1,1,"yellow", "orange");
console.log(colors); // ["red", "yellow", "orange", "blue"]
console.log(removed); // ["green"]

Date与RegExp类型详解

Date类型与RegExp类型


var pattern1 = /[bc]/i;
var pattern2 = new RegExp("[bc]at", "i");

pattern1和pattern2是两个完全等价的正则表达式。需要注意的是,传递给RegExp构造函数的两个参数都必须是字符串,不能直接传递正则表达式字面量。由于RegExp构造函数的模式参数被视为字符串,因此在某些情况下需要对字符串进行双重转义处理。


var pattern1 = /[bc]/i;
var pattern2 = new RegExp("\\[bc\\]at", "i");

RegExp实例方法中的exec方法

exec接收一个参数,即要应用模式的字符串,然后返回包含第一个匹配信息的数组。


var text = "cat, bat, sat, fat";
var pattern1 = /.at/;

var matches = pattern1.exec(text);
console.log(matches); // ["cat"]

match方法用于在字符串中执行正则表达式匹配,其参数为正则表达式对象。


var text = "cat, bat, sat, fat";
var pattern1 = /.at/;

var matches2 = text.match(pattern1);
console.log(matches2); // ["cat"]

test()接收一个字符串参数,用于测试该字符串是否匹配正则表达式。


var text = "000-00-0000";
var pattern = /\d{3}-\d{2}-\d{4}/;

if (pattern.test(text)){
  console.log("The pattern was matched"); // The pattern was matched
}

Function类型内部机制

Function类型涉及函数内部属性,包括将arguments对象转换为数组的方法。


(function() {
  var slice = Array.prototype.slice,
    aArguments = slice.apply(arguments);

    console.log(aArguments);
})(10, 20, 30);
arguments.callee

该属性是一个指针,指向拥有这个arguments对象的函数。当函数在严格模式下运行时,访问arguments.callee会导致错误。

函数属性和方法中的length属性表示函数希望接收的命名参数的个数。


function sayName(name){
  alert(name);
}

function sum(num1,num2){
  return num1 + num2;
}

function sayHi(){
  alert("hi");
}

console.log(sayName.length); //1
console.log(sum.length); //2
console.log(sayHi.length); //0

prototype属性

call和apply方法用于改变函数执行时的this指向。


function sum(num1, num2){
  return num1 + num2;
}

function callSum1(num1,num2){
  return sum.apply(this,arguments);
}

function callSum2(num1, num2){
  return sum.apply(this, [num1, num2]); 
}

console.log(callSum1(10,10)); // 20
console.log(callSum2(10,10)); //20
window.color = "red";
var o = {color:"blue"};

function sayColor(){
  console.log(this.color);
}

sayColor(); // red

sayColor.call(this); // red
sayColor.call(window); // red
sayColor.call(o); // blue

基本包装类型与字符串处理

基本包装类型


var value = "25";
var number = Number(value);
console.log(typeof number);
console.log(number instanceof Number);// false

var obj = new Number(value);
console.log(typeof obj);
console.log(obj instanceof Number);// true

Boolean类型


var falseObject = new Boolean(false);
var result = falseObject && true; // true 

//布尔表达式中的所有对象都会被转换为true, 因此falseObject对象在布尔表达式中代表的是true

console.log(result); // true

var falseValue = false;
result = falseValue && true;
console.log(result); //false

console.log(typeof falseObject); //object
console.log(typeof falseValue); // Boolean
console.log(falseObject instanceof Boolean); //true
console.log(falseValue instanceof Boolean); // false

Number类型


var numberObject = new Number(10);
var numberValue = 10;
console.log(typeof numberObject); // Object
console.log(typoef numberValue); // number
console.log(numberObject instanceof Number); // true
console.log(numberValue instanceof Number); // false

String类型包含字符操作方法,如charAt()和charCodeAt()。

charAt()方法以单字符字符串的形式返回给定位置的那个字符串。

charCodeAt()返回的是字符编码。


var stringValue = "hello world";
console.log(stringValue.charAt(1)); // e
console.log(stringValue.charCodeAt(1)); // 101

字符串操作方法中的concat()。

concat()用于将一或多个字符串拼接起来。


var stringValue = "hello ";
var result = stringValue.concat("world");
console.log(result); // hello world
console.log(stringValue); // hello

slice(start, end)中end表示字符串到哪里结束。如果传入的是负数,slice()方法会将传入的负值与字符串长度相加。


var str="Hello happy world!";
console.log(str.slice(6)); // happy world!
console.log(str.slice(6,11));// happy
console.log(str.slice(-3)); // ld!
console.log(str.slice(3, -4)); //lo happy wo 

substring(start, end)中,如果传入的是负数,substring()会把所有字符参数都转换为0。


var str="Hello happy world!";
console.log(str.substring(6)); // happy world!
console.log(str.substring(6,11));// happy
console.log(str.substring(-3)); // Hello happy world!
console.log(str.substring(3, -4)); //Hel

substr(start, length)中,如果传入的是负数,substr()方法将负的第一个参数加上字符串的长度,而将负的第二个参数转换为0。


var str="Hello world!";
console.log(str.substr(3)); //lo world!
console.log(str.substr(3, 7)); //lo worl
console.log(str.substr(-3)); // ld!
console.log(str.substr(3, -3)); // 空字符串

字符串位置方法


indexOf() lastIndexOf()

var stringValue = "hello world";
console.log(stringValue.indexOf("o")); // 4
console.log(stringValue.lastIndexOf("o")); //7

这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。


var stringValue = "hello world";
console.log(stringValue.indexOf("o", 6)); // 7
console.log(stringValue.lastIndexOf("o", 6)); //4

字符串的模式匹配方法中的match()。


var text = "cat, bat, sat, fat";
var pattern = /.at/;

var matches = text.match(pattern);
console.log(matches.index); //0
console.log(matches[0]); // cat
console.log(pattern.lastIndex); //0

search()方法。


var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos); // 1

replace()方法。


var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
console.log(result); // cond, bat, sat, fat

var result = text.replace(/at/g, "ond");
console.log(result); // cond, bond, sond, fond

Global对象与Math随机数生成

Global对象包含URI编码方法。Global对象的encodeURI()和encodeURIComponent()方法可以对URI(Uniform Resources Identifiers,通用资源标识符)进行编码,以便发送给浏览器。


var url = "http://www.baidu.com/";
console.log(encodeURI(url));
console.log(encodeURIComponent(url));
encodeURI()和encodeURIComponent()方法对象的两个方法分别是decodeURI()和decodeURIComponent()

Math对象中的random()方法。

Math.random()方法返回介于0和1之间一个随机数,不包含0和1。对于某些站点来说,这个方法非常实用,因为可以利用它来随机显示一些名言和新闻事件。套用下面的公式,就可以利用Math.random()从某个整数范围内随机选择一个值。


值=Math.floor(Math.random()*可能值的总数+第一个可能的值)

例如:如果想选择一个1到10之间的数值,可以像下面这边编写代码:


var num = Math.floor(Math.random()*10+1);
function selectFrom(lowerValue,upperValue){
  var choice = upperValue - lowerValue + 1;
  return Math.floor(Math.random()*choice+lowerValue);
}
var num = selectFrom(2,10);
console.log(num);
var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var color = colors[selectFrom(0, colors.length-1)];
console.log(color);

作者最新文章