JS中对象可以定义为三种:自定义对象、内置对象、浏览器对象,其中:
一、自定义对象定义方式有三种:
(1)利用字面量定义对象
var obj = {
uname: "张三",
age: 18,
sex: "男",
sayHi: function () {
console.log("hi~");
},
};
console.log(obj.name);
console.log(obj.name);
boj.sayHi();
(2)利用new Object定义对象
var obj = new Object();
obj.uname = '张三';
obj.age = 18;
obj.sex = '男';
obj.sayHi = function() {
console.log('hi~');
}
调用方式同上;
如果需要定义多个不同对象,则需要多次重复该代码
(3)利用构造函数创建对象
function Star(uname, age, sex) {
this.name = uname;
this.age = age;
this.sex = sex;
this.sing = function(sang) {
console.log(sang);
}
}
var ldh = new Star('刘德华', 18, '男');
var zxy = new Star('张学友', 19, '男');
console.log(ldh.name);
ldh.sing('冰雨');
可重复调用构造函数,创建对象,推荐!
二、内置对象
比较常用内置对象有:
Math对象、Date日期、Array数组、String字符串,具体见后文!
三、浏览器对象(BOM)
BOM对象包含DOM对象,DOM的顶级对象是document,而BOM的顶级对象是window,它是一个全局对象。
定义在全局作用域中的变量、函数都会变成window对象的属性和方法。在调用的时候可以省略window,一般都是省略了的;
具体包含结构如下:
JS内置对象及常用方法
Math对象
注意:除了Math.PI(属性),上面的方法必须带括号,因为是在调用已封装对象(内置对象)的方法;
另外:Math.random()方法
Math.random() 方法可以随机返回一个小数,其取值范围是[0,1),左闭右开0 <= x < 1,这个方法里面不跟参数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; // 公式
}
console.log(getRandom(1, 10));
Date日期
Date 对象和 Math 对象不一样,他是一个构造函数,所以我们需要实例化后才能使用;
Date 实例用来处理日期和时间;
注意:
// 1. 使用Date() 如果括号里面没有参数 返回当前系统的当前时间
var date = new Date();
console.log(date);
// 2. 如果括号里面有时间,就返回参数里面的时间;
// 参数常用的写法 数字型 2019, 10, 01 或者是 字符串型 '2019-10-1 8:8:8'
var date1 = new Date(2019, 10, 1);
console.log(date1); // 返回的是 11月 不是 10月
var date2 = new Date('2019-10-1 8:8:8');
console.log(date2);
得到:
// 格式化日期 年月日
var date = new Date();
console.log(date.getFullYear()); // 返回当前日期的年 2020
console.log(date.getMonth() + 1); // 月份 返回的月份小1个月 记得月份+1
console.log(date.getDate()); // 返回的是 几号
console.log(date.getDay()); // 周一返回的是 1 周六返回的是 6 但是 周日返回的是 0
// 写一个 2020年 11月 1日 星期三
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var day = date.getDay(); // 当前星期数的值,1234560
console.log('今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day]);
// 格式化日期 时分秒
var date = new Date();
console.log(date.getHours()); // 时
console.log(date.getMinutes()); // 分
console.log(date.getSeconds()); // 秒
// 要求封装一个函数返回当前的时分秒 格式 08:08:08
function getTimer() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
console.log(getTimer());
// 倒计时案例:把剩余时间总的毫秒数转换为天、时、分、秒 (时间戳转换为时分秒)
// 转换公式如下:
// d = parseInt(总秒数/ 60/60 /24); // 计算天数
// h = parseInt(总秒数/ 60/60 %24) // 计算小时
// m = parseInt(总秒数 /60 %60 ); // 计算分数
// s = parseInt(总秒数%60); // 计算当前秒数
// 获得Date总的毫秒数(时间戳) 不是当前时间的毫秒数 而是距离1970年1月1号过了多少毫秒数
// 1. 通过 valueOf() getTime()
var date = new Date();
console.log(date.valueOf()); // 就是 我们现在时间 距离1970.1.1 总的毫秒数
console.log(date.getTime());
// 2. 简单的写法 (最常用的写法)
var date1 = +new Date(); // +new Date() 返回的就是总的毫秒数
console.log(date1);
// 3. H5 新增的 获得总的毫秒数
console.log(Date.now());
function countDown(time) {
var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
var inputTime = +new Date(time); // 返回的是用户输入时间总的毫秒数
var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数
var d = parseInt(times / 60 / 60 / 24); // 天
d = d < 10 ? '0' + d : d;
var h = parseInt(times / 60 / 60 % 24); //时
h = h < 10 ? '0' + h : h;
var m = parseInt(times / 60 % 60); // 分
m = m < 10 ? '0' + m : m;
var s = parseInt(times % 60); // 当前的秒
s = s < 10 ? '0' + s : s;
return d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(countDown('2020-10-1 18:00:00'));
var date = new Date();
console.log(date);
Array数组
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array (更多参考MDN文档)
Array.push()
该方法将一个或者多个值追加到数组末尾,并返回该数组的新长度;
var arr = ["red", "green", "blue"];
var newLength = arr.push("black");
console.log(newLength); // 4
console.log(arr); // ["red", "green", "blue", "black"]
Array.pop()
该方法将从数组末尾删除并返回最后一个元素;
var myFish = ["angel", "clown", "mandarin", "surgeon"];
var popped = myFish.pop();
console.log(myFish);// ["angel", "clown", "mandarin"]
console.log(popped);// surgeon
Array.unshift()
该方法将一个或多个元素添加到数组的开头,并返回该数组的新长度;
var arr = [1, 2];
arr.unshift(0); // arr is [0, 1, 2]
arr.unshift(-2, -1); // arr is [-2, -1, 0, 1, 2]
arr.unshift([-4, -3]); // arr is [[-4, -3], -2, -1, 0, 1, 2]
arr.unshift([-7, -6], [-5]);// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
Array.shift()
该方法从数组中删除第一个元素,并返回该元素的值;
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);// Array [2, 3]
console.log(firstElement);// 1
Array.reverse()
该方法将数组中元素的位置颠倒,并返回该数组;
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);// "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);// "reversed:" Array ["three", "two", "one"]
Array.sort()
方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的;
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);// Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);// Array [1, 100000, 21, 30, 4],此类方法仅能按照个位数排序;
// 完美写法:
var numbers = [44, 2, 5, 1, 3];
numbers.sort(function (a, b) {
return a - b; // 升序排列;return b-a 会降序排列
});
console.log(numbers);
//也可以写成:
var numbers = [44, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); // 箭头函数
console.log(numbers);
//都得到:// [1, 2, 3, 5,44]
Array.indexOf()
方法返回在数组中找一个指定元素的第一个索引,如果不存在,则返回 -1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
console.log(beasts.indexOf('giraffe'));
// expected output: -1
console.log(beasts.indexOf('bison', 2)); //从索引为2的位置开始找起,无则返回-1
// expected output: 4
案例:找出指定元素所有出现的位置
var newArr = [];
var array = ["a", "b", "a", "c", "a", "d"];
var element = "a";
var idx = array.indexOf(element);
while (idx != -1) {
newArr.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(newArr); // [0, 2, 4]
Array.lastIndexOf()
方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3); // 从索引为3的位置开始
// index is 3
index = array.lastIndexOf(2, 2); // 从索引为2的位置开始向前找
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3
Array.toString()
返回一个字符串,表示指定的数组及其元素。
var array1 = [1, 2, "a", "1a"];
console.log(array1.toString());
// expected output: "1,2,a,1a"
var str = 1234;
console.log(typeof(str)); // number
var newStr = str.toString();
console.log(newStr + 999); // 1234999
Array.join()
方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
const elements = ['Fire', 'Air', 'Water'];
const array = ['你好'];
console.log(elements.join());
// expected output: "Fire,Air,Water" // 默认是以逗号分隔
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
console.log(array.join('-')); // "你好"
Array.concat()
方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。如果如果忽略了扩号内的参数,则 concat
会返回调用此方法的现存数组的一个浅拷贝(地址)。
var num1 = [1, 2, 3],
num2 = [4, 5, 6],
num3 = [7, 8, 9];
var nums = num1.concat(num2, num3);
console.log(nums); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
var alpha = ['a', 'b', 'c'];
var alphaNumeric = alpha.concat(1, [2, 3]);
console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3]
var num1 = [[1]];
var num2 = [2, [3]];
var num3=[5,[6]];
var nums = num1.concat(num2);
console.log(nums); // results is [[1], 2, [3]]
var nums2=num1.concat(4,num3);
console.log(nums2)
// results is [[1], 4, 5,[6]]
Array.slice()
方法返回一个新的数组对象,这一对象是一个由 begin
和 end
决定的原数组的浅拷贝(包括 begin
,不包括end
)。原始数组不会被改变。如果 end
被省略 或者 大于数组的长度,slice
会一直提取到原数组末尾。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(0, 4));
// expected output: Array ["ant", "bison", "camel", "duck"]
Array.splice()
方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
语法:Array.splice( start,deleteCount,items );
如果 deleteCount
:
添加。
>0,则是替换,
大于 start
之后的元素的总数,则从 start
后面的元素都将被删除(含第 start
位)。
const months = ['一', '二', '三', '四'];
months.splice(1, 0, '添加1'); // inserts at index 1
console.log(months);// Array ["一", "添加1", "二", "三", "四"]
months.splice(4, -1, '添加2');// replaces 1 element at index 4
console.log(months); //Array ["一", "添加1", "二", "三", "添加2", "四"]
months.splice(4, 1, '替换1');// replaces 1 element at index 4
console.log(months);// Array ["一", "添加1", "二", "三", "替换1", "四"]
months.splice(1, 3, '我一人顶三个');// replaces 1 element at index 4
console.log(months);// Array ["一", "我一人顶三个", "替换1", "四"]
months.splice(1, 9999, '我一人顶三个');// replaces 1 element at index 4
console.log(months);// Array ["一", "我一人顶三个"]
另外:
得到:
如果没有 items,则相当于删除数据,此处是从索引为2开始,删除一个,也就是“3”
Array.find()
语法:arr.find(callback[, thisArg])
方法对数组中的每一项元素执行一次 callback
函数,直至有一个 callback 返回 true
。返回数组中满足提供的测试函数的第一个元素的值,否则返回 undefined。
另,findIndex() 方法,它返回数组中找到的元素的索引,而不是其值。
如果你需要找到一个元素的位置或者一个元素是否存在于数组中,使用 indexOf() 或 includes()。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // 12,立即停止查找,并返回
const array2 = [5, 12, 8, 130, 44];
const found2 = array2.find(function(e){
return e>=10
});
console.log(found2); // 12
const array3 = [5, 12, 8, 130, 44];
const found3 = array3.find(test);
function test(e){
return e>=10
};
console.log(found3); // 12
三种方式而已。。
案例:
案例一:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
案例二:
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined
console.log([4, 5, 8, 12].find(isPrime)); // 5
案例三:
var a = [0,1,,,,5,6];
a.find(function(value, index) {
console.log('Visited index ' + index + ' with value ' + value);
});
得到:
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value 5
// Visited index 6 with value 6
案例四:
var a = [0,1,,,,5,6];
a.find(function(value, index) {
if (index == 0) {
console.log('Deleting a[5] with value ' + a[5]);
delete a[5]; // 注:这里只是将a[5]设置为undefined,可以试试用a.pop()删除最后一项,依然会遍历到被删的那一项
}
console.log('Visited index ' + index + ' with value ' + value);
});
得到:
//"Deleting a[5] with value 5"
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value undefined
// Visited index 6 with value 6
Array.findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
var array1 = [5, 12, 8, 130, 44];
var aaaa = (element) => element > 13;
console.log(array1.findIndex(aaaa)); // 3
var array1 = [5, 12, 8, 130, 44];
var bbbb = function (a) {
return a >= 13;
};
console.log(array1.findIndex(bbbb)); // 3
var array2 = [5, 12, 8, 130, 44];
function cccc(a) {
return a >= 13;
}
console.log(array2.findIndex(cccc)); // 3
其余同find()类似。
Array.includes()
方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false 从索引为3的位置开始搜索,无
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
Array.some()
方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。可用于检测数组中是否含有某个值。
some()
为数组中的每一个元素执行一次 callback
函数,直到找到一个使得 callback 返回一个“真值”(即可转换为布尔值 true 的值)。如果找到了这样一个值,some()
将会立即返回 true
。
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
[2, 5, 8, 1, 4].some(x => x > 10); // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
此例中为模仿 includes() 方法, 若元素在数组中存在, 则回调函数返回值为 true
var fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
return arr.some(function(arrVal) {
return val === arrVal;
});
}
checkAvailability(fruits, 'kele'); // false
checkAvailability(fruits, 'banana'); // true
Array.map()
方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1); // Array [2, 8, 18, 32]
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles数组的值为: [2, 8, 18]
// numbers数组未被修改: [1, 4, 9]
Array.filter()
方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); // Array ["exuberant", "destruction", "present"]
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // [12, 130, 44]
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
function filterItems(query) {
return fruits.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
Array.forEach()
方法对数组的每个元素执行一次给定的函数。
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
const arraySparse = [1,3,,7];
let numCallbackRuns = 0;
arraySparse.forEach(function(element){
console.log(element);
numCallbackRuns++;
});
console.log("numCallbackRuns: ", numCallbackRuns);
// 1
// 3
// 7
// numCallbackRuns: 3
const items = ['item1', 'item2', 'item3'];
const copy = [];
// before
for (let i=0; i<items.length; i++) {
copy.push(items[i]);
}
// after
items.forEach(function(item){
copy.push(item);
});
String字符串
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String (更多参考MDN文档)
String.chartAt()
方法从一个字符串中返回指定的字符。字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1
。
如果指定的 index 值超出了该范围,则返回一个空字符串。
var anyString = "Brave new world";
console.log("The character at index 0 is '" + anyString.charAt(0) + "'");
console.log("The character at index 1 is '" + anyString.charAt(1) + "'");
console.log("The character at index 2 is '" + anyString.charAt(2) + "'");
console.log("The character at index 3 is '" + anyString.charAt(3) + "'");
console.log("The character at index 4 is '" + anyString.charAt(4) + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
// The character at index 0 is 'B'
// The character at index 1 is 'r'
// The character at index 2 is 'a'
// The character at index 3 is 'v'
// The character at index 4 is 'e'
// The character at index 999 is ''
String.concat()
方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。
let hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day.
let greetList = ['Hello', ' ', 'Venkat', '!']
"".concat(...greetList) // "Hello Venkat!"
"".concat({}) // [object Object]
"".concat([]) // ""
"".concat(null) // "null"
"".concat(true) // "true"
"".concat(4, 5) // "45"
String.split()
方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。 如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。
const str = 'The quick brown fox dog.';
const words = str.split(' ');
console.log(words);
console.log(words[3]); // "fox"
const chars = str.split('');
console.log(chars);
console.log(chars[8]); // "k"
const strCopy = str.split();
console.log(strCopy); // Array ["The quick brown fox jumps over the lazy dog."]
// Array ["The", "quick", "brown", "fox", "dog."]
// "fox"
// Array ["T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "d", "o", "g", "."]
// "k"
// Array ["The quick brown fox dog."] 分隔符为空字符串,则将str原字符串中每个字符的数组形式返回
String.slice()
语法:String.slice( beginIndex, endIndex)
方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
console.log(str.slice(-4));
// expected output: "dog."
console.log(str.slice(-9, -5));
// expected output: "lazy"
String.substr()
语法:String.slice( start, end)
方法返回一个字符串中从指定位置开始到指定字符数的字符。
var str = "abcdefghij";
console.log("(1,2): " + str.substr(1,2)); // (1,2): bc
console.log("(-3,2): " + str.substr(-3,2)); // (-3,2): hi
console.log("(-3): " + str.substr(-3)); // (-3): hij
console.log("(1): " + str.substr(1)); // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): " + str.substr(20,2)); // (20, 2):
String.substring()
方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集;
substring
提取从 indexStart
到 indexEnd
(不包括)之间的字符。特别地:
- 如果
indexStart
等于indexEnd
,substring
返回一个空字符串。 - 如果省略
indexEnd
,substring
提取字符一直到字符串末尾。 - 如果任一参数小于 0 或为 NaN,则被当作 0。
- 如果任一参数大于
stringName.length
,则被当作stringName.length
。 - 如果
indexStart
大于indexEnd
,则substring
的执行效果就像两个参数调换了一样。见下面的例子:
var anyString = "Mozilla";
// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));
// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// 输出 ""
console.log(anyString.substring(4,4));
// 输出 "Mozill"
console.log(anyString.substring(0,6));
// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
String.trim()
两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)
const greeting = ' Hello world! ';
console.log(greeting);
// expected output: " Hello world! ";
console.log(greeting.trim());
// expected output: "Hello world!";
String.replace()
方法返回一个由替换值(replacement
)替换部分或所有的模式(pattern
)匹配项后的新字符串。
模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern
是字符串,则仅替换第一个匹配项。
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi; // 正则表达式
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
在 replace() 中使用 global 和 ignore 选项
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
console.log(newstr); // oranges are round, and oranges are juicy.
String.replaceAll()
方法返回一个新字符串,新字符串所有满足 pattern
的部分都已被replacement
替换。
pattern
可以是一个字符串或一个 RegExp, replacement
可以是一个字符串或一个在每次匹配被调用的函数。
原始字符串保持不变。
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi;
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
String.includes()
方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1)); // false
console.log(str.includes('TO BE')); // false
String.indexOf()
语法:String.indexOf(searchValue,fromIndex)
方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex
处进行搜索。如果未找到该值,则返回 -1。
var str = 'hello world';
console.log(str.indexOf('w')); // 6
console.log(str.indexOf('w',1)); // 6
若被查找的字符串 searchValue 是一个空字符串,将会产生“奇怪”的结果。如果 fromIndex 值为空,或者 fromIndex 值小于被查找的字符串的长度,返回值和以下的 fromIndex 值一样:
'hello world'.indexOf('') // 返回 0
'hello world'.indexOf('', 0) // 返回 0
'hello world'.indexOf('', 3) // 返回 3
'hello world'.indexOf('', 8) // 返回 8
另外,如果 fromIndex 值大于等于字符串的长度,将会直接返回字符串的长度(str.length):
'hello world'.indexOf('', 11) // 返回 11
'hello world'.indexOf('', 13) // 返回 11
'hello world'.indexOf('', 22) // 返回 11
String.lastIndexOf()
方法返回调用String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex
处从后向前搜索。如果没找到这个特定值则返回 -1 。
lastIndexOf 方法区分大小写。例如,下面的表达式返回 -1:
"Blue Whale, Killer Whale".lastIndexOf("blue"); // -1
var anyString = "Brave new world";
console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// Displays 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// Displays 10
console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// Displays 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// Displays 6
String.toLowerCase()
会将调用该方法的字符串值转为小写形式,并返回。
console.log( "ALPHABET".toLowerCase() ); // "alphabet"
String.toUpperCase()
方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toUpperCase());// "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."