宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

一、JS转数组的方法

JavaScript中,我们可以使用多种方法将字符串、集合或类数组转换为数组。下面是一些实用的JS转数组的方法:

1. Array.from()

const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']

Array.from()方法将字符串转换为字符数组。

2. slice()

const str = 'hello';
const arr = Array.prototype.slice.call(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']

slice()方法将字符串转换为字符数组,然后使用函数调用将该数组复制到新数组中。

3. split()

const str = 'hello world';
const arr = str.split(' ');
console.log(arr); // ['hello', 'world']

split()方法将字符串分割为数组。

二、JS数组去重

数组去重是常见的操作,避免相同的值被计算多次。下面是几种常用的JS数组去重方法:

1. 借助Set去重

const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 4, 5]

使用Set去重,然后转化为数组。

2. 使用forEach去重

const arr = [1, 2, 2, 3, 4, 4, 5];
let newArr = [];
arr.forEach((item) => {
  if (!newArr.includes(item)) {
    newArr.push(item);
  }
});
console.log(newArr); // [1, 2, 3, 4, 5]

使用forEach()循环数组,判断元素是否在新数组中,如果不存在则添加到新数组中。

三、数组转字符串JS/字符串转数组JS

在JavaScript中,我们可以轻松地将数组转换为字符串或将字符串转换为数组。

1. 数组转字符串JS

const arr = ['h', 'e', 'l', 'l', 'o'];
const str = arr.join('');
console.log(str); // 'hello'

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

2. 字符串转数组JS

const str = 'hello';
const arr = str.split('');
console.log(arr); // ['h', 'e', 'l', 'l', 'o']

使用split()方法将字符串分割为字符数组。

四、数组转JSON

JavaScript中的数组转JSON是一种将数据从JS格式转换为JSON格式的方法,JSON格式的数据可以用于Web应用程序之间的数据交换。

const arr = [{name:'John', age:20}, {name:'Mary', age:18}];
const json = JSON.stringify(arr);
console.log(json); // '[{"name":"John","age":20},{"name":"Mary","age":18}]'

使用JSON.stringify()方法将数组对象转换为JSON字符串。

五、JS数组反转/数组反转JS

在JavaScript中,我们可以使用reverse()方法反转数组。

const arr = ['h', 'e', 'l', 'l', 'o'];
const reverseArr = arr.reverse();
console.log(reverseArr); // ['o', 'l', 'l', 'e', 'h']

使用reverse()方法反转数组。

六、JS转字符串/JS数组循环/JS数组转换为对象

1. JS转字符串

const obj = {name:"John", age:20};
const str = JSON.stringify(obj);
console.log(str); // '{"name":"John","age":20}'

使用JSON.stringify()方法将对象转换为JSON字符串。

2. JS数组循环

const arr = ['h', 'e', 'l', 'l', 'o'];
arr.forEach(function (item) {
  console.log(item);
});

使用forEach()方法循环遍历数组。

3. JS数组转换为对象

const arr = [['name', 'John'], ['age', 20]];
const obj = Object.fromEntries(arr);
console.log(obj); // { name: 'John', age: 20 }

使用Object.fromEntries()方法将数组转换为对象。

总结

在JavaScript中,我们可以轻松地将字符串、集合或类数组转换为数组,去重数组,将数组转换为字符串或将字符串转换为数组,将数组对象转换为JSON字符串以进行数据交换,并使用reverse()方法反转数组。我们还可以使用forEach()方法循环数组和使用Object.fromEntries()方法将数组转换为对象。