因为容易搞混数组和字符串的方法,所以特地总结了一下
数组和字符串都有的方法:
concat、includes、indexOf、lastIndexOf、slice、toString
数组中concat:
concat()
方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
字符串中的concat
concat
方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。concat
方法并不影响原字符串。
数组中的includes:
includes()
方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
var pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
字符串中的includes:
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('nonexistent')); // false
数组中的indexOf
indexOf()
方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
字符串中的indexOf
indexOf()
方法返回调用 String
对象中第一次出现的指定值的索引,开始在 fromIndex进行搜索。
如果未找到该值,则返回-1。
"Blue Whale".indexOf("Blue"); // returns 0
"Blue Whale".indexOf("Blute"); // returns -1
数组中的lastIndexOf:
lastIndexOf()
方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex
处开始。
字符串中的lastIndexOf:
lastIndexOf()
方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找,从 fromIndex
处开始。
数组中的slice:
slice()
方法返回一个新的数组对象,这一对象是一个由 begin
和 end
(不包括end
)决定的原数组的浅拷贝。原始数组不会被改变。
var 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(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
字符串中的slice:
slice()
方法提取一个字符串的一部分,并返回一新的字符串。
var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);
console.log(str2); // OUTPUT: morning is upon u
数组中的toString:
toString()
返回一个字符串,表示指定的数组及其元素。
var array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"
字符串中的toString:
toString()
方法返回指定对象的字符串形式。
var x = new String("Hello world");
alert(x.toString()) // 输出 "Hello world"