判断数组为空

const arr = [];
if(arr.length === 0) {
    console.log('arr为空')
}

判断数组是否包含某个值

  1. arr.indexOf()
if(arr.indexOf(2) !== -1) {
    console.log('数组含有2');
}else{
    console.log('数组不含2');
}
  1. arr.includes() ES6新方法
const arr = [1, 2, 3, 4];
if(arr.includes(2)) {
    console.log('数组中有2');
}else{
    console.log('数组中无2');
}

数组转字符串

const arr = ['hello', 'world', '!'];
const str = arr.join(' '); //hello world !

字符串转数组

const str = 'hello,world,!';
const arr = str.split(','); //helloworld!

数组元素颠倒顺序

const arr1 = ['hello','world','!'];
const arr2 = arr1.reverse(); //['!', 'world', 'hello']
Scroll to Top