JavaScript字符串,数组,Math常用方法

目录

字符串方法

slice(start,end):返回字符串中提取的子字符串

// 截取字符串时不包括下标为end的元素。
// end是可选参数,没有时,默认从start到结束的所有字符串。
var str="Hello World";
var str1=str.slice(1); // 如果只有一个参数,则提取开始下标到结尾处的所有字符串
var str2=str.slice(2,8); // 两个参数,提取下标为2,到下标为8但不包含下标为8的字符串
var str3=str.slice(-7,-2); // 如果是负数,-1为字符串的最后一个字符。提取从下标-7开始到下标-2但不包含下标-2的字符串。前一个数要小于后一个数,否则返回空字符串

console.log(str1); // ello World
console.log(str2); // llo Wo
console.log(str3); // o Wor

// substring(): 提取字符串中介于两个指定下标之间的字符
// 注意:substring()用法与slice()一样,但不接受负值的参数。
var str="Hello World";
var str1=str.substring(2)
var str2=str.substring(2,2);
var str3=str.substring(2,7);
console.log(str1); //llo World
console.log(str2); //如果两个参数相等,返回长度为0的空串
console.log(str3); //llo W

substr(start,end):返回从指定下标开始指定长度的子字符串

// substr(): 返回从指定下标开始指定长度的的子字符串
// 注意:如果没有指定length,返回从下标开始处结尾处的所有字符串。
var str="Hello World";
var str1=str.substr(1)
var str2=str.substr(1,3);
var str3=str.substr(-3,2);
console.log(str1); // ello World 
console.log(str2); // ell
console.log(str3); // rl

indexOf(): 返回某个指定的子字符串在字符串中第一次出现的位置

// 注意:indexOf()方法对大小写敏感,如果子字符串没有找到,返回-1
// 第二个参数表示从哪个下标开始查找,没有写则默认从下标0开始查找
var str="Hello World";
var str1=str.indexOf("o");
var str2=str.indexOf("world");
var str3=str.indexOf("o",str1+1);
console.log(str1); // 4 默认只找第一个关键字位置,从下标0开始查找
console.log(str2); // -1 没有找到
console.log(str3); // 7

// lastIndexOf(): 返回某个指定的子字符串在字符串中最后出现的位置。
// 注意:lastIndexOf()方法对大小写敏感,如果子字符串没有找到,返回-1
// 第二个参数表示从哪个下标开始查找,没有写则默认从最后一个字符处开始查找。
var str="Hello World";
var str1=str.lastIndexOf("o");
var str2=str.lastIndexOf("world");
var str3=str.lastIndexOf("o",str1-1);
console.log(str1); //7
console.log(str2); //-1
console.log(str3); //4

// includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false
// includes() 方法是区分大小写的
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false

split(): 把字符串分割成字符串数组

var str="AA BB CC DD";
var string1="1:2:3:4:5";
var str1=str.split("");//如果把空字符串 ("")用作分割符,那么字符串的每个字符之间都会被分割
var str2=str.split(" "); //以空格为分隔符
var str3=str.split("",4); //4指定返回数组的最大长度
var str4=string1.split(":");
console.log(str1); // ["A", "A", " ", "B", "B", " ", "C", "C", " ", "D", "D"]
console.log(str2); //["AA" "BB" "CC" "DD"]
console.log(str3); //["A", "A", " ", "B"]
console.log(str4); // ["1", "2", "3", "4", "5"]

replace(): 在字符串中用一些字符替换另一些字符

var str="hello WORLD";
// 替换一个与正则表达式匹配的子串
var reg=/o/ig; //o为要替换的关键字,不能加引号,否则替换不生效,i忽略大小写,g表示全局查找。
var str1=str.replace(reg,"**")
console.log(str1); //hell** W**RLD
var str1 = str.replace('l', "*")
console.log(str1); //he*lo WORLD,只替换第一个匹配的字符

trim():去除前后两端的空格

let r = '  rqz  '
console.log(r.trim());	// rqz

toLowerCase(): 把字符串转为小写,返回新的字符串。

var str="Hello World";
var str1=str.toLowerCase();

toUpperCase(): 把字符串转为大写,返回新的字符串。

var str="hello world";
var str1=str.toUpperCase();

charAt(): 返回指定下标位置的字符。

var str="hello world";
var str1=str.charAt(6);

charCodeAt(): 返回指定下标位置的字符的unicode编码

// 这个返回值是 0 - 65535 之间的整数
var str="hello world";
var str1=str.charCodeAt(1);
var str2=str.charCodeAt(-2); //NaN,实参不能为负数
console.log(str1); //101
// 注意:如果index不在0-str.length(不包含str.length)之间,返回NaN

match(): 返回所有查找的关键字内容的数组

var str="To be or not to be";
var reg=/to/ig;
var str1=str.match(reg);
console.log(str1); //["To", "to"]
console.log(str.match("Hello")); //null
console.log(str.match("or")); // ["or", index: 6, input: "To be or not to be", groups: undefined]

数组方法

splice()对数组进行删除修改,返回被删除的元素组成的数组,改变原数组

// splice(index,length,增加的元素1,增加的元素2....,增加的元素N) 
// 表示从index开始删除length个元素,并从index开始新增元素1~N,放回被删除的元素组成的数组
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);	// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
console.log(months);	// expected output: Array ["Jan", "Feb", "March", "April", "May"]

join() 方法用来将数组转换为字符串

// 不改变原数组,返回转换后的字符串
var a = [1,2,3,4,5]
let b = a.join('')
console.log(b);	// 12345
console.log(a.join(','))  // 1,2,3,4,5
console.log(a)  // [1,2,3,4,5]

高级函数

// filter() 方法返回数组中满足条件的元素组成的新数组,原数组不变
var a = [1,2,3,4,11]
// 第一个参数为一个方法,有三个参数,current:当前值 index:当前值下标 array:这个数组对象
var b = a.filter(function(current,index,array){
    return current < 10
})
console.log(b) // [1,2,3,4]
console.log(a) // [1,2,3,4,11]

// map() 方法来根据需求格式化原数组,返回格式化后的数组,原数组不变
var a = [1,2,3,4,5]
// 第一个参数为一个方法,有三个参数,current:当前值 index:当前值下标 array:这个数组对象
var b = a.map(function(current,index,array){
    return current + 1
})
console.log(b) // [2,3,4,5,6]
console.log(a) // [1,2,3,4,5]

// reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值
/* reducer 函数接收4个参数:
Accumulator (acc) (累计器)
Current Value (cur) (当前值)
Current Index (idx) (当前索引)
Source Array (src) (源数组)
reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值 */
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
const array  = [5,4,7,8,9,2];
array.reduce((a,b) => a+b);	// 求和,输出: 35
array.reduce((a,b) => a>b?a:b);	// 最大值,输出: 9
array.reduce((a,b) => a<b?a:b);	// 最小值,输出: 2

// every()  对数组的每一项都运行给定的函数,若每一项都返回 ture,则返回 true
var a = [1,2,3,4,5]
var b = a.every(function(current,index,array){
       return current < 6
})
var c = a.every(function(current,index,array){
       return current < 3
})
console.log(b)  // true 
console.log(c)  // false 

// some()	对数组的每一项都运行给定的函数,若存在一项或多项返回 ture,则返回 false
var a = [1,2,3,4,5]
var b = a.some(function(current,index,array){
       return current > 4
})
var c = a.some(function(current,index,array){
       return current > 5
})
console.log(b)  // true 
console.log(c)  // false 

// forEach()	遍历整个数组,中途不能中断
var arr = ['a','b','c']
var copy = []
arr.forEach(function(item){
     copy.push(item)   
})
console.log(copy)

// find()	找到数组中第一次满足条件的元素,并返回,若找不到则返回undefined,不改变原数组
var a = [1,2,3,4]
// b在下面需要使用,则一般用find
var b = a.find(function(ele,index,array){
    return ele == 1
})
var c = 3
var d = b + c
console.log(a) // [1,2,3,4]
console.log(b) // 1
console.log(d) // 4

// findIndex()的作用同indexOf(),返回第一个满足条件的下标,并停止寻找
// 区别是findIndex() 的参数为一个回调函数,且一般用于对象数组
var a = [1,2,3,4]
var b = a.findIndex(function(ele,index,array){
    return ele === 2
})
var c = a.indexOf(2)  
console.log(a)  // [1,2,3,4]
console.log(b)  // 1
console.log(c)  // 1

// includes()方法,返回一个布尔值。 参数是一个value,一般用于简单数组
// 对于复杂数组,则可以使用some()方法替代includes()方法
var a = [1,2,3]
console.log(a.includes(1))  // true

// Array.isArray()方法,用来判断一个元素是否为数组
Array.isArray([])  // true
Array.isArray({})  // false

push():向数组后添加一个新的元素,并返回新数组的长度

// 末尾添加,返回长度,改变原数组
var a = [1,2,3]
var b = a.push(5)
console.log(a)  // [1,2,3,5] 
console.log(b)  // 4

unshift()可以向数组前添加一个或多个元素,并返回新的长度

// 首部添加,返回长度,改变原数组
var a = [2,3,4]
var b = a.unshift(0,1)
console.log(a)  // [0,1,2,3,4]
console.log(b)  // 5

pop() 用于删除并返回最后一个元素

// 尾部删除,返回被删除的元素,改变原数组
var a = [1,2,3]
var b = a.pop()
console.log(a) // [1,2]
console.log(b) // 3

shift() 用于删除并返回首个元素

// 删除首部元素,返回被删元素,改变原数组
var a = [1,2,3]
var b = a.shift()
console.log(a) // [2,3]
console.log(b) // 1

indexOf()和lastIndexOf():查找某元素在数组中的位置

// indexOf(某元素,startIndex) 从startIndex开始,查找某元素在数组中的位置,若存在,则返回第一个位置的下标,否则返回-1
// lastIndexOf(某元素,startIndex) 和indexOf()相同,区别在于从尾部向首部查询
// 不会改变原数组,返回找到的index,否则返回-1
// 若不使用下标,则一般通过includes()方法代替indexOf()
var a = [1,2,4,3,4,5]
console.log(a.indexOf(4))  // 2
console.log(a.indexOf(4,3)) // 4
// includes()方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false
// includes() 方法是区分大小写的
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));	// expected output: true
console.log(pets.includes('at'));	// expected output: false

concat() 拼接

var a = [1,2,3]
var b = [4,5]
var c = a.concat(b)
console.log(a) // [1,2,3]
console.log(b) // [4,5]
console.log(c) // [1,2,3,4,5] 

slice() 剪切

// slice(startIndex,endIndex)  返回从startIndex开始(包括),到endIndex(不包括)之间的原属组成的数组
// 返回新数组,不改变原数组
var a = [1,2,3]
var b = a.slice(0,1)
// 不填参数则表示剪切整个数组  
var c = a.slice() 
console.log(a) // [1,2,3] 
console.log(b) // [1]
console.log(c) // [1,2,3]    
console.log(a===c)  // false // 注意 a !== c 
var d = a.slice(-1,-2)   
console.log(d) // []   负数表示从后往前数,所以说为[]
var e = a.slice(-1)  
console.log(e)  // [3]
var f = a.slice(-2)
console.log(f)	// [2, 3]

排序

// sort() 排序,按ascii码排序,改变原数组,返回排序后的数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();	// 输出 (4) ["Joe", "Kapil", "Musk", "Steve"]
// 先将数组进行升序排序,然后用reverse将升序反过来,就是倒序排序
stringArr.reverse();	// 输出 (4) ["Steve", "Musk", "Kapil", "Joe"]
// 排序数字数组
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);	// (6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);	// (6) [100, 40, 25, 10, 5, 1]
array.sort((a,b) => {return b-a});	// 有{}后,需要加上return
// 对象数组排序
const objectArr = [ 
    { first_name: 'Lazslo', last_name: 'Jamf'     },
    { first_name: 'Pig',    last_name: 'Bodine'   },
    { first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出
(3) [{}, {}, {}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3

// reverse() 颠倒顺序,方法用于颠倒数组中元素的顺序,返回的是颠倒后的数组,会改变原数组
var a  = [1,3,2,7,6]
console.log(a.reverse())  // [6,7,2,3,1]
console.log(a)  // [6,7,2,3,1]

从数组中过滤出虚假值

// 0,undefined,null,false,"",''可以很容易地通过以下方法省略
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]

删除重复值

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]

打乱数组

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

Math方法

Math称为数学函数,但是它属于对象类型的

typefo Math //=> “object”

绝对值

Math.abs(10)   // => 10
Maht.abs(-10)  //=> 10

向上或向下取整

// ceil向上取整
Math.ceil(10)  //=> 10
Math.ceil(10.01)  // =>11
Math.ceil(-10.01)  //=>-10
// 向下取整
Math.floor(10.999)  //=> 10 
Math.floor(-10.099)  //=> -11

四舍五入

Math.round(10.49)  // =>10
Math.round(10.5) //=>11
Math.round(-10.49) // => -10
Math.round(-10.5) // =>-10
Math.round(-10.51) // => -11

获取0~1之间的随机小数

Math.round(Math.random() * (100))
Math.round(Math.random()*(m-n)+n)
// Math.round(Math.random()*(m-n)+n): 获取n~m之间随机整数(到临界点的概率比较低)

开平方

Math.sqrt(100)  //=>10
Math.sqrt(10)  // =>3.1627766
Math.sqrt(16)  // =>4

取幂(N的M次方)

Math.pow(2,10)  // => 1024

获取最大值和最小值

Math.max(12,23,34,15,26)  // => 34
Math.min(12,23,34,15,26)  // => 12

获取圆周率

Math.PI  // = 3.141592654

提升效率的方法

对各种条件使用逻辑运算符

// 如果你想减少嵌套 if…else 或 switch case,你可以简单地使用基本的逻辑运算符AND/OR
function doSomething(arg1){ 
    arg1 = arg1 || 10; 
// 如果尚未设置,则将 arg1 设置为 10 作为默认值
	return arg1;
}
let foo = 10;  
foo === 10 && doSomething(); 
// is the same thing as if (foo == 10) then doSomething();
// 输出: 10
foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// 输出: 10

创建计数器对象或映射

// 大多数情况下,需要通过创建计数器对象或映射来解决问题,该对象或映射将变量作为键进行跟踪,并将其频率/出现次数作为值进行跟踪。
let string = 'kapilalipak';
const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}

三元运算符很酷

function Fever(temp) {
    return temp > 97 ? 'Visit Doctor!'
      : temp < 97 ? 'Go Out and Play!!'
      : temp === 97 ? 'Take Some Rest!';
}
// 输出
Fever(97): "Take Some Rest!" 
Fever(100): "Visit Doctor!"

可选链

// 可选的链接 ?.如果值在 ? 之前,则停止评估。为 undefined 或 null 并返回
const user = {
  employee: {
    name: "Kapil"
  }
};
user.employee?.name;
// 输出: "Kapil"
user.employ?.name;
// 输出: undefined
user.employ.name
// 输出: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined

空合并算子

// 空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
const foo = null ?? 'my school';
// 输出: "my school"
const baz = 0 ?? 42;
// 输出: 0

将十进制转换为二进制或十六进制

const num = 10;
num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"

使用解构简单交换两值

let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]	// 输出 (2) [8, 5]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值