今日直接把两个数组进行比较,发现js中是不能直接比较两个数组是否相等的。即使里面的元素都是一样的,但最后结果认为 false 。一般都是把数组转换为字符串,然后进行比较。
数组如何变成字符串:
1、使用join 字符串变量名.join()
let a = [1,2,3,4,5];
let s = a.join("+"); //确定连接符为+
console.log(s); // '1+2+3+4+5'
2、使用toString 或者 toLocalString
var arr=[1,2,3,4,5];
let str = arr.toString()
let str1 = arr.toLocaleString()
console.log(str)// '1,2,3,4,5'
console.log(str1)// '1,2,3,4,5'
补充:
字符串数组变成数组:
1、split() 方法用于把一个字符串分割成字符串数组。split() 方法不改变原始字符串。
数组变量名.split()
var str='hello world!';
var n=str.split();
var m=str.split('');
console.log(n)
console.log(m)
结果:
[ 'hello world!' ]
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o','r', 'l', 'd', '!']
2、 使用ES6 中的 ... 扩展符 。
var str='hello world!';
console.log([...str])
结果:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o','r', 'l', 'd', '!']
3、使用ES6中的 Array.from 方法
Array.from(字符串变量名)
let str = 'hello world!';
console.log(Array.from(str)) // ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o','r', 'l', 'd', '!']