trim()
函数的基本概念
trim()
函数用于删除字符串两端的空格(空格、制表符、换行符等)。其基本语法如下:
string.trim();
string
:要操作的字符串。
去除字符串两端的空格
const text = " Hello, World! ";
const trimmedText = text.trim();
console.log(trimmedText); // 输出:"Hello, World!"
在这个例子中,我们首先有一个包含前后空格的字符串 text
,然后使用 trim()
函数将其两端的空格去除,得到了修剪后的字符串。
unshift()
函数的基本概念
unshift()
函数用于向数组的开头添加一个或多个元素,并返回修改后的数组的长度。其基本语法如下:
array.unshift(item1, item2, ...);
array
:要操作的数组。item1, item2, ...
:要添加到数组开头的元素。
向数组开头添加元素
const fruits = ["apple", "banana", "cherry"];
fruits.unshift("grape", "orange");
console.log(fruits); // 输出:["grape", "orange", "apple", "banana", "cherry"]
在这个例子中,我们使用 unshift()
函数向 fruits
数组的开头添加了两个新元素,即 “grape” 和 “orange”。